Entity Framework doesn't work with stored procedures! - c#

Is it true that you cannot call an sp with the EF unless the sp returns an entity?
To test I created 3 Function Imports for an sp with 1. no return type 2. a scalar return type and 3. an entity return type
then when i type "DataContext" then "." I only get intellisense on the function that returns an entity!
I'm surprised this isn't a current feature!
What are people using as a workaround?

There is a workaround!
Julie Lerman wrote a post about this. Have a look at her blog: http://thedatafarm.com/blog/data-access/implement-select-stored-procedures-that-return-miscellaneous-data-in-ctp2-of-ef-designer/
It helped me a lot to implement my stored procedures.

Has to return an entity, yes.

Using powerful T4 templates
Entity Framework V1.0 feels and is an unfinished product set out to public too early. That's why it's possible to use T4 templates that create different code from EDMX files, that also supports scalar-type stored procedures.
We're using custom templates with lots of modifications so they create Business layer objects, interfaces for IoC/TDD as well as DAL and DAO. We get everything from EDMX files. Heck we even create enums but those are created from real data in the DB not EDMX files.
You'll be able to find lots of T4 templates...
Here's one that does scalar stored procedures. But you may want to get one that actually does POCO.

In EF v1 you can only map procedures which return entities. In EF v4 you can map procedure results to complex types, so most procedures can be used without returning entities.
Use Chrigl's answer (+1) as a workaround for v1.

Related

Hierarchyid data type and Code First

What I need to do, I have a comment table using the HierarchyID data type in sql server, and would like that mapped over to a Code First/EF 4.3 class. How can I achieve this?
Also how do I interact with the hierarchyID when inserting/deleting. Thank you very much.
This is a possible duplicate of HierarchyID in Entity Framework not working
EF does not support that data type http://thedatafarm.com/blog/data-access/sql-server-2008-data-types-and-entity-framework-4/
I'm not used to the data type, but I've carried out some investigations.
Seems like this type is supported only inside the SQL Server both natively and in hosted CLR. Getting it outside requires it to be converted to a string (see Data Type Conversion section here).
I think the only way is creating a view in the database converting the hierarchyid to nvarchar(4000). To make it updatable you can either define a set of insert/update/delete triggers for that view, or create a set of corresponding stored procedures and map them to the EF context. I don't remember if EF Code First is capable of using SPs for modification operations, but an updatable view should be fine since it looks like an ordinary table.
Hope this helps.

Easily create database tables from logical model in .NET and VS

Background:
I started to create logical database model for ASP.NET MVC web site. I used visual designer for Entity framework that ships with VS because I have used it before.
But now I already have 33 classes and I'm not finished (including quite some inheritance and a lot of associations). I'm afraid that it would be too complicated and time consuming for me to manually set all the table mappings and than generate database tables. I've no experience with it - I've done it the other way: classes from database tables and it took me a lot of time to get it work in a smaller project.
Question:
How can I easily and quickly create database tables for logical model (class diagram) in .NET / VS ? It would be great if it was possible automatically. I have never worked with LinqToSQL visual designer and it seems to be no reference on the web on how to create database tables from LinqToSQL classes. Is it possible at all ? If not is there any way to create database tables with Entity framework automatically - without having to specify table mappings ?
And one side question: if I used LinqToSQL classes are that going to commit changes to database every time I change properties ? Or is some caching taking place there ?
Entity framework has a concept called "Model First", which generates the database model from you model, hence the name.
You can read about that here: http://msdn.microsoft.com/en-us/data/ff830362
However, my personal favourite when it comes to Object Relational Mappers is NHibernate with the addition Fluent NHibernate. They have a concept where you work with your domain model rather than you data model and you use conventions to control your mappings. It's pretty neat. You can get started with some pretty good examples by looking at this code here: https://github.com/sharparchitecture/Northwind/tree/master/app
Linq2Sql is too limited for the case you are talking about. And it has no capability to generate data models from code. In fact, Linq2Sql works the other way around - it generates a set of classes from your data model, much like Entity Framework also can do.
Neither Linq 2 SQL or Entity Framework commit anything until you explicitly choose to do so. They both have a notion of a object context which keeps track of all changes made. When you call "Save", they transform those changes into SQL which is then executed in the database.
Like MikeEast, I've had a very good experience with Fluent NHibernate.
On my project, I use the Automapping feature, which allows me to change my data model almost at will, and the database schema automagically gets updated.
No SQL, no worrying about foreign keys, etc, etc, etc - I love it!
Fluent NHibernate Automapping
Finally I have sticked with Entity framework - tables generating is really plainless once I learnt how to deal with database connections...

Manually Link Stored Procedure To LINQ

I have a Stored Procedure that returns a dynamic result set based on a temporary table. My project uses LINQ for Data Access, but I can't incorporate LINQ with this Stored Procedure because it has a dynamic "shape" (I can't say before hand which columns will come back or how many there will be), so LINQ can't generate at design time an object that can hold the results.
I am trying to integrate the stored procedure the old fashioned was, using SQLDataAdapter and such, but I was hoping that I could still tie into LINQ so that I don't need to manage a separate transaction mechanism as that would be a disaster.
Is this possible? Thanks.
One best practice is that a stored procedure should never be coded such that it gives different columns in a result set based on inputs.
It sounds like your design is causing the single stored proc to try and do too many things. I'd highly suggest you change this.
First - you aren't using "LINQ" for data access. My guess is you are using Entity Framework for data access. If you are, it depends on which version of EF you are using.
New in Entity Framework 4 is shaping data from a stored proc. For step-by-step instructions, see this blog post: http://blogs.msdn.com/b/nihitk/archive/2010/04/23/ado-net-entity-designer-in-vs-2010-stored-procedure-return-type-shape-sensing.aspx
If you are using Entity Framework 1, which comes with .NET 3.5, then no EF does not have the ability to sense the shape of the stored proc data.

c# ado.net : best way to map database fields to property

Using VS2005, .net 2.0 , C#
Hi all,
What is the best way to map stored proc columns to the c# object properties with out creating tight coupling.
For example, I dont like to do the following
DataRow row = Getmyrows();
MyObject.MyProperty1 = row["col1"];
MyObject.MyProperty2 = row["col2"];
So, when the column in stored proc gets changed to colxyz then the binary code will break. What is the best practice to address this. A code sample would be helpful and thank you in advance.
I would look into OR mappers. LINQ to SQL, nHibernate, Entity Framework, LLBLGen, etc. These allow you to configure your mapping via XML or some other external configuration source. Most of them also provide a way to completely decouple your entities from the persistence framework, allowing your entities to be POCO (Plain Old CLR Objects). Another benefit of OR mappers is they generate SQL for you on the fly, which allows you to largely eliminate your stored proc layer, which is also a coupling that can cause problems (on both ends...in your code as well as in your DB schema.)
Couple approaches:
If you're forced to stick w/ ADO.NET proper, use a strongly typed dataset. All that mapping between objects and data structures is down in a schema where it belongs. Then you'd be able to hydrate your objects w/ code like this:
MyObject.MyProperty1 = dataSet.TableName.PropertyName
I noticed everyone else said the same thing I was going to ;-) Go w/ an ORM. I know premature optimization is a slippery slope, but you inevitably will find clear justification for going that route. You won't regret it as your requirements become more complex, and you'll be learning a valuable skillset that's clearly gaining a lot of momentum in the .NET space.
Best solution is to use a proper O/RM like NHibernate, or if you can settle for "less" Linq to SQL or Entity Framework.
However if you must, I suggest using IDataReader/SqlDataReader instead (simplest, best performance), but you won't get away with having to map to column names if you want to do it the "hard way".
An approach that coworkers and I used back in the 2.0 days was to create a custom attribute which we used to specify the field name from the data table, and tagged our objects' properties with it. then built a generic entity builder that would take a datareader as a parameter ( EntityBuilder(IDataReader rdr) ); as it worked through the datareader, it would create an empty T, reflect on the class, go through the properties to get the custom attribute information and the type, and set the value based on that.
also had another custom attribute that specified the parameter used in our Insert and Update SPROCs to automatically populate the parameters, too.
If you have to do it that way, and dont want to use ORM, store the column names mapping in an xml file.
<appSettings>
<key="prop1" value="col1">
</appSettings>
then in the code do something like:
myObject.Prop1 = ConfigurationManager.AppSettings["prop1"].Value
I know its clunky, and involves reading from xml (or the config file) for each property but it will work.

Simple Mapper Pattern C# Code Generation Template

Can anybody recommend a decent C# Mapper Pattern code generation template that plays nicely with SQL stored procedures? I'm looking for something that generates POCO style entity objects, with a static mapper class for transferring data to/from the database through entity objects.
I understand that NHibernate can generate POCO style entity objects; however, NHibernate looses its appeal when you have a strong dependency on SQL stored procedures (which is a requirement of this project).
Bonus points awarded if you can also recommend a template that also generates the CRUD stored procs! ;-)
Edit: For this particular project, I am definitely not interested in any templates that generate Active Record pattern code (e.g, Subsonic, Linq to SQL, Entity Framework, etc.).
The very old, but free LLBLGen will generate CRUD stored procedures. It will also generate objects, but I forget how much like POCOs they are. I have a feeling there are more guts in them than not.
http://www.codeproject.com/KB/database/usingllblgen.aspx
Have you looked at using My Generation and using it to create your own templates?

Categories