How to map a Stored proc result to an existing DA class - linq

When I use SQLMetal to create the linq version of one of my stored procs it creates a returned class specific to the proc - I want to map the result to an existing DA table class.
any ideas?

I would advise switching from LINQ to SQL to Entity Framework. This is a known issue and has been resolved in EF4 as it allows you to map the return of an SP to a particular data structure.

Related

Does Entity Framework automatically load all of my data (not a reference and lazy load is off)?

I have a database first Entity Framework project. For every entity that I add, a collection is added to the DbContext for the entity. I explicity set LazyLoadingEnabled = false in the DbContext constructor. If I break into the following code and check the count of CustomerDepartments, I get the total count of the table. If I'm just adding a new record, I expect the count to be 0 before I add, and 1 after. I'm using this in a stateless environment, so loading the whole table just to add a record seems absurd. What am I doing wrong?
using (Model.SupportEntities support = new Model.SupportEntities(_state.Credentials, _handler.ReadWriteConnectionString))
{
Model.CustomerDepartment department = Json.JsonConvert.DeserializeObject<Model.CustomerDepartment>(_insertObject);
support.CustomerDepartments.Add(department);
support.SaveChanges();
_state.ReturnNewIdAsJson(department.CustomerDepartmentID);
}
It seems you have misinterpreted how DbContext and DbSet works.
It maybe best if you get hold of a tool for logging EntityFramework SQL calls try Clutch.Diagnostics.EntityFramework.
When you call IEnumerable<T>.Count() on DbSet<T>, Entity Framework runs the following query
SELECT COUNT(*) FROM TableName;
But it does not load the whole table.
The ACTUAL call you want for the behavior you wanted was either
support.CustomerDepartments.Local.Count;
OR
support.ChangeTracker.Entries<T>().Count()
These will NOT hit the database.
You have to remember that DbSet is an abstraction for the Database table, so calling Count() on it should tell you how many rows there are in the table.
BTW. FYI. The convention is call name your DbContext to be SupportContext. Model named classes or namespace suggests they are your POCOs.

Replacing EF4.1 with ADO.net when calling stored proc in MVC3?

I need to replace EF4.1 with ADO.NET. The data in our application is returned by stored procedures only. I need help re-writing calls like the following (in order to write a DAL for the application):
EF calling stored procedure:
using (var db = new NexGenContext())
{
SqlParameter param = new SqlParameter("#ReviewID", Id);
var issues = db.Database.SqlQuery<QuestionIssue>(
"SP_GetQuestionIssues #ReviewID", param).ToList();
return View(issues);
}
What is the equivalent in ADO.NET? Get data from the database and map to my models?
The closest ADO.NET technology to being an ORM without actually crossing the line is data sets. Data sets act very much like an ORM in the way you can access data directly from a table without looping through a cursor. Data Sets return lists directly and can track new data vs old.
This link is a pretty good overview:
http://www.c-sharpcorner.com/UploadFile/718fc8/working-with-dataset-in-ado-net/
This MVC datasets with viewbags stack thread specifically addresses using Data Sets in Models.

linq to sql, how to define DataContext without specifying Table properties

My intent is to create a generic (not in C# meaning) database model for Windows Phone using linq to sql. User of such model should be able to pass an array of his data object types (classes marked with Table attribute) to model's contstructor, and then model should take care about adding related tables to database and provide API for CRUD operations.
But then I've found out that in order to add tables to database, your data context (class inherited from DataContext class) have to declare each table as a property! That's embarrassing. Does this fact mean that my idea is not implementable? Because I obviously cannot add properties to my DataContext-based in the runtime.
So my question is, am I right in my judgments? If yes, are there some workarounds to solve this issue?
Thanks in advance.
EDIT: better question tagging, for somebody finally notice this.
You do not need to use a strongly typed DataContext (a class inheriting from DataContext and declaring properties for each table). You can do something like the following instead
var context = new DataContext("connection string", new AttributeMappingSource());
var table = context.GetTable<T>();
where T is some type marked with the Table attribute.

Adding a Stored Proc to complex type not showing up in .edmx (thus not mapped)?

1 (mvc3) I have added a stored proc to my model as mapped to a ComplextType.
Two Issues:
1) ComplextType.cs exists in class under Model1.tt BUT doesn't show up in .edmx?
2) When I try to create a controller with strongly typed views with that ComplexType.cs it errors stating that it can't be created because ComplextType.cs is not part of the DbContextEntities class?
How can I get this complex type added to the .edmx and mapped to my dbcontext (I have done this with tables but not sure what I'm missing for the stored procedures?
Thanks!
For those who just came here from googling,, :)I will give the what is basically has to be done to map a stored procedure into a ADO.Net entity.
When mapping the Database to the EDMX file(Entity Model).. the Entity Model automatically map the tables and complex types and ect.. But the stored procedures that are created in the database is not mapped with return complex types. We have to map it in the Function imports by creating our own complex type. This complex type can be accessed in the code.
This is done as below:
Right click on the function Import and add new Function import.
Give your name to the function and specify the stored procedure and
then select complex type(If stored procedure returns complex type)
or you can select scalar. IF you are selecting the complex type and
you can view the columns that are returning and you can create a complex there by create new complex type.
So the return data from the stored procedure will be a set of those complex type.
One thing that should be one should access the design or the model view to update the Entity Model. You can not update the Entity Model by just right clicking on the Entity Model. The option of updating the model is provided only on the Model Browser and the Database design diagram. This model browser can be taken from the Other windows of Views in VS2010/VS2012. These information will seems boring. But trust me if you are new to this these seems big at the beginning.
Most probably you are going to create this Entity Model from mapping an existing database.
Keep in mind that even you map the Entity model form the database you can customize the Entity model by deleting the unnecessary entities(tables) and creating complex types

.NET 3.5 Linq Datasource and Joins

Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?
If the tables are connected by a foreign key, you can easily reference both tables as they will be joined by linq automatically (you can see easily if you look in your dbml and there is an arrow connecting the tables) - if not, see if you can add one.
To do that, you can just use something like this:
<%# Bind("unit1.unit_name") %>
Where in the table, 'unit' has a foreign key that references another table and you pull that 'unit's property of 'unit_name'
I hope that makes sense.
(EDIT misunderstood the question, revising my answer to the following)
Your LinqDataSource could point to a view, which allows you to overcome the problem of not being able to express a Join in the actual element. From "How to: Create LINQ to SQL Classes Mapped to Tables and Views (O/R Designer)":
The O/R Designer is a simple object relational mapper because it supports only 1:1 mapping relationships. In other words, an entity class can have only a 1:1 mapping relationship with a database table or view. Complex mapping, such as mapping an entity class to multiple tables, is not supported. However, you can map an entity class to a view that joins multiple related tables.
You cannot put more than one object/datasource on a datagrid. You will have to build a single ConceptObject that combines the exposed properties of the part Entities. Try to use DB -> L2S Entities -> ConceptObject. You must be very contrived if the DB model matches the ConceptObject field-for-field.
You are best using a ObjectDataSource when you wnt to do more complex Linq and bind your Grid to the ObjectDataSource.
You do however need to watch out for Anonymous types that could give you some trouble, but anything is posible...

Resources