Basic Entity Framework Questions - asp.net-mvc-3

I have an existing database, which I have been happily accessing using LINQtoSQL. Armed with Sanderson's MVC3 book I thought I'd have a crack at EF4.3, but am really fighting to get even basic functionality working.
Working with SQL 2008, VS2010, the folder architecture appears to be:
ABC.Domain.Abstract
ABC.Domain.Concrete
ABC.Domain.Concrete.ORM
ABC.Domain.Entities
Per examples, repository interfaces are abstract, actual repositories are concrete. Creating EDMX from the existing database puts that in the ORM folder and the Entities holds the classes I designed as part of the domain. So far so good.
However! I have not once persuaded the deceptively simple EfDbContext : DbContext class, with method to work...
public DbSet<ABC.Domain.Entities.Person> Person { get { return _context.Persons; }}
It complains about missing keys, that Person is not a entity class, that it cannot find the conceptual model, and so on.
Considering I have a basic connectionstring in the web.config, why is not creating a model on the fly to do simple matching?
Should the ORM folder exist, or should it simply be Concrete? (I have a .SQL subfolder for LINQtoSQL concret so it suits me to have .ORM but if it's a flaw, let's fix it).
Should I have my homespun entities AND the automatically produced ones or just one set?
The automatic ones inherit from EntityObject, mine are just POCO or POCO with complexTypes, but do not inherit from anything.
What ties the home designed Domain.Entities.Person type to the Persons property of the Context?
Sanderson's book implies that the matching is implicit if properties are identical, which they are, but that does not do it.
The app.config has an EF flavoured connection string in it, the web.config has a normal connection string in it. Which should I be using - assuming web.config at the moment - so do I delete app.config?
Your help is appreciated. Long time spent, no progress for some days now.

What ties the home designed Domain.Entities.Person type to the Persons
property of the Context?
You seem to have a misunderstanding here. Your domain entities are the entities for the database. There aren't two sets. If you actually want to have two sets of object classes (for whatever reason) you must write any mapping between the two manually. EF only knows about the classes which are part of the entity model.
You should also - if you are using EF 4.3 - apply the DbContext Generator T4 template to the EDMX file. Do not work with EntityObject derived entities! It is not supported with DbContext. The generator will build a set of POCO classes and prepare a derived DbContext. This set of POCO classes are the entities the DbContext will only know about and they should be your only set of domain entities.
The created DbContext will contain simple DbSet properties with automatic getters and setters...
public DbSet<Person> People { get; set; }
...and the Person class will be created as POCO as well.

Download the entity framework power tools:
http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
Right click in your project to 'reverse engineer an existing database' it will create the code classes for you. No need to use EDMX ,and this method will create the DbContext derived class for you

There are many questions here and you won't get an answer, but I'll stick my 5 pence for what it's worth.
Sanderson's MVC3 book
Your problems are not to do with MVC3, they are to do with Entity Framework and data persistence layer.
ABC.Domain.Abstract ABC.Domain.Concrete ABC.Domain.Concrete.ORM
ABC.Domain.Entities
Can you say why this is separated in such a way? I would argue and say that ABC.Domain should contain your POCOs independent of your persistence layer (EF) and your presentation layer (MVC). Your list implies that your domain contains ORM and your data access entities. I'm not arguing here, what I'm trying to say, is that you need to understand what you really need.
At the end of a day, I'm certain that a simple example would suffice with ABC.DataAccess, ABC.Domain and ABC.Site.
Do you understand why repositories are abstract and concrete? If you don't, then leave out interfaces and see whether you can improve it with interfaces later.
Person is not a entity class, that it cannot find the conceptual
model, and so on.
Now, there are multiple ways you can get EF to persist data for you. You can use code first, where, as the name implies, you will write code first, and EF will generate database, relations and all the relevant constraints for you.
You can use database first, where EF will generate relevant class and data access related objects from your database. This is less preferable method for me, as it relies heavily upon your database structure.
You can use model first, where you will design your class in EDMX designer and it will then generate relevant SQL for you.
All of these might sound like a bit of black box, but for what you are trying to achieve all of them will work. EDMX is a good way to learn and there are many step by step tutorials on ASP.Net.
but if it's a flaw, let's fix it).
You will have to fix and refactor yourself, there is no other way to improve in my honest opinion. I can give you a different folder/namespace structure, but there will always be a "better" one.
Should I have my homespun entities AND the automatically produced ones
or just one set?
Now this depends on the model that you have chosen. Database first, code first, code only and whatever else is there. If you are following domain driven development, then you will have to work with classes, that represent your business logic and that are not tied up to your data persistence layer or presentation layers, therefore POCO is a way forward.
What ties the home designed Domain.Entities.Person type to the Persons
Now this again depends on the model that you are using.
The app.config and web.config
When you are running your web application, the connection string from web application will be used. Please correct me if I'm wrong.
Your help is appreciated. Long time spent, no progress for some days
now.
General advise, leave MVC alone for the time being. Get it to work in a console application and make sure you feel comfortable with options offered in EF. Good luck :)

The solution to why nothing worked code-first...
...turned out to be a reference to System.Data.EntityClient in the connection string, which ought to have read System.Data.SqlClient.
Without this provider entry being correct, it was unable to work code-first.
Finding which connectionString it was using was a case of deliberately mis-spelling a keyword in the connections there were to choose from - they all were named correctly - but were in app.config, and 2 places in the web.config. With a distinct naming error, when the application threw an error trying to create the domain model, it was easy to identify which connection string my derived DbContext class was using. Correcting the ProviderName made all the difference.
Code-first is now working just fine, with seeded values on model changes.

Related

EF to ADO.NET transition

Need suggestion for migration few modules of asp.net mvc 3 application:
Right now we are using EF with POCO classes, but in the future for some performance driven modules we need to move to ADO.NET or some other ORM tool (may be DAPPER.NET).
The issue we are facing as of now is: our views dependent on Collection classes getting loaded through EF, what strategy should i used for these entity classes to be get loaded exactly the same way as by EF with some other ADO.NET or ORM tool.
What i want is to be able to switch between EF & ADO.NET with minimum of change at data access layer, as i don't want my Views to get effect by that.
You should use the Repository Design Pattern to hide the implementation of your data access layer. The Repository will return the same POCO's and have the same operations contracts no matter what data access layer you are using underneath the hood. Now this works fine if you are using real POCO's that do not have virtual methods for lazy loading in them. You will need to explicitly handle loading of dependent collections on entities to make this work.
What I've seen so far, a seamless transition from one ORM/DAL to another is an illusion. The repository pattern as suggested by Kevin is a great help, a prerequisite even (+1). But nonetheless, each ORM has a footprint in the domain layer. With EF you probably use virtual properties, maybe data annotations or, easily forgotten, a validation framework that easily fits in (and dismiss others that don't). You may rely on EF's ability to map across join tables. There may be things you don't (but would like to) do because of EF.
(Not to mention tools that execute scaffolding on top of an EF context. That would make the lock-in even tighter.)
Some things I might do in your situation (forgive me if I'm stating the obvious for you)
Use EF optimally. (Best mappings, best associations, ...) Preparing for the future is good, but it easily degenerates into the YAGNI pattern.
Become proficient in linq + EF: there are many ways to needlessly kill performance with EF. Suppose EF is good enough!
Keep looking for alternatives for high performance, like using stored procedures, parallellization, background processing, and/or reducing data volumes, and choose one when the requirements (functional and non-functional) are clear enough.
Maybe introduce an abstraction layer with DTO's that serve your views now, and in the future can be readily materialized by another ORM or ADO.
Expose POCO's as interfaces, which can be implemented by other objects later.
Just to add to both of these answers...
I always structure my solution into these basic projects:
Front end (usually asp.net MVC web app),
Services/Core with business processes,
Objects with application model POCOs and communication interfaces - referenced by all other projects so they serve as data interchange contracts and
Data that implements repositories that return POCO instances from Objects
Front end references Objects and Services/Core
Services Core references Objects and Data
Data references Objects
Objects doesn't reference any of the others, because they're the domain application model
If front end needs any additional POCOs I create those in the front end as view models and are only seen to that project (ie. registration process usually uses a separate type with more (and different) properties than Objects.User entity (POCO). No need to put these kind of types in Objects.
The same goes with data-only types. If additional properties are required, these classes usually inherit from the same Objects class and add additional properties and methods like generic ToPoco() method that knows exactly how to map from data type to application mode class.
Changing DAL
So whenever I need to change (which is as #GetArnold pointed out) my data access code I only have to provide a different Data project that uses different library/framework. All additional data-specific types etc. are then part of it as well... But all communication with other layers stays the same.
Instead of creating a new Data project you can also change existing one, by changing repository code and use a different DAL in them.

Confused: Why to do i have to map my entity object to viewmodel object

i am a complete newbie to the entity framework,mvc just started with it 3 weeks ago.
From then i have been beating around the bush searching for the right approach.the more i dig the more i get lost...i am afraid that i could not proceed any further with using entity framework in mvc
I m lost and frustrated :(
what i have been trying to do is to use entity framework for the MVC application.For that i have started with creating an School.edmx file(which has School.Designer.cs automatically created for it.I dont have any POCO or any others just plain edmx with designer class).Then through some searching i have found that its bad practice to use entity object as model for view.....
Now the real thing started i have made a viewmodel for an entity object.The thing is i dont really get why i have to use a repository and why do i have to map my entity objects and viewmodel objects.Everytime i search why i have to map i get some links saying how to use automapper and the more i search about repository the more i get lost .i dont even understand it.why do i have to map ...??? and why do i have to use repository.
And now the other thing i ask repeatedly to myself is why do i have to write data annotation again in the Viewmodel class when i have already data annotated it in my designer.cs file (like [Required],[Email] and other annotations)..? WHY to write them again!! (If i dont mention them in viewmodel i dont see the annotations working). Duplication of annotation...?
I am lost and i dont even know where i m now
someone give me the right path to follow
Yours Sincerely,
Lost & Confused Newbie
Don't Fret!
Entity Framework is a big beast of a framework based on another beast of a framework: ADO.NET. It's very difficult to truly understand Entity Framework apart from understanding ADO.NET.
That being said, Entity Framework is the perfect tool in some scenarios. However, you (like many of us) seem to have a disconnect about the roles of EF, ASP.NET MVC, and a Repository.
The thing is, you don't need a repository. You don't even need a view model. You don't need EF. And you don't even need ASP.NET MVC. All of these tools are used to make specific jobs easier. None of them have direct ties to each other, and any of them can be used independently of each other.
A Repository: is used to put certain objects into some persistent place, so that you can get them later. That's really all it is.
ASP.NET MVC: Is an HTTP Handler that takes the requested URL and instantiates a controller class which in turn serves up views. The views display some model, and because the views are interactive, they allow the user to send yet another request, starting the whole thing over again. Because this process is (intentionally, but not necessarily) stateless, some sort of persistence is required. This persistence can be a file on the server, a file database, or in most cases a relational database.
Entity Framework: sits on top of ADO.NET (Microsoft's relational database abstraction framework), and allows you to map objects from a graphical (in memory) form to a relational (in-database) form, and back again. The idea is to allow the developer to easily map objects to and from the database. However, this is not a simple process, and because you're not directly interacting with the database (be it via ADO.NET or not), there is some inherent complexity. One of those complexities is the display of the information.
View Models (asp.net mvc view models): allow models to be displayed in various forms. For instance, we may have a "scholastic record" table, and a "person" table, and together they might form a "student". Because our entities are "ScholasticRecord" and "Person", we cannot (as) simply display the information on the view. For this reason, we create a view model to combine and display the information as a "Student".
View Models also prevents us from accidentally calling "lazy" methods on our entities while in the view, which might query the database. This isn't bad, but it could get confusing, because our view is doing repository-like work (which isn't very [S]OLID).
TLDR;
The reason you're having trouble is probably because you're trying to do everything at once. I would suggest using the tools you know, in addition to maybe one or two that you do not. Try using Entity Framework and ASP.NET MVC together, but don't worry about the Repository pattern just yet. It can be difficult to use EF with a Repository, unless you have a lot of experience with either or both.
ASP.NET MVC Tutorials with Entity Framework:
http://www.asp.net/mvc/tutorials/mvc-music-store
(notice how they use models directly in the view, sometimes)
The thing is i dont really get why i have to use a repository
MVC helps you write code that has a clear separation of concerns. In this case, the repository is meant to how the application interacts with the data storage for a specific entity. If you want a Student entity you call StudentRepository.GetEntity(). If you want to save to save you call the StudentRepository.SaveEntity(Student student).
Why do i have to map my entity objects and viewmodel objects.Everytime i search why i have to map i get some links saying how to use automapper and the more i search about repository the more i get lost.
While you can use these entities directly in your view for simple cases, the problem comes up when you have more complex views - composite views that may need multiple entities, views that need to expose only a subset of an entity or even a subset of multiple entities. So yes, you can just expose your entity directly but I find it easier just to create a separate view model.
Automapper is used to help map from view model to entity. So, instead of writing a lot of
entity.Name = viewModel.Name;
entity.Age = viewModel.Age;
...
Automapper is used to automatically map these properties.
And now the other thing i ask repeatedly to myself is why do i have to write data annotation again in the Viewmodel class when i have already data annotated it in my designer.cs file (like [Required],[Email] and other annotations)..?
You should specify validation logic specific for each view in the view model so that if validation fails at the controller it can stop processing instead of continuing. Even though mapping your view model to an entity and trying to save would be prevented by the entities data annotation, I find it clearer to look at a view and its view model to understand what's going on instead of going from view to view model to entity.
Update:
Take a look at ASP.NET MVC View Model Patterns and How we do MVC – View models. I found them both useful when trying to understand view models.

entity framework model first repository confusion

I'm not sure if the repository patter is just the most common thing i'm seeing or if it is the best practices for abstracting a layer between the database and the controller. found some good resources today explaining persistence ignorance and why it's good for unit testing. However I still feel unclear on a proper entity framework implementation.
my current project, I went about creating the model first. i can safely say my aggregate roots are:
Business
User
Event
Invoice
these roots are fairly rich with references to "look-up entities" in the model. That is to say that my model contains 20 some odd entities, a number of which are used primarily for look-up purposes. If i were to implement the repository patter,
do i need to create a POCO for each entity?
Do i ever reference the auto-generated EF classes/entites as attributes of a repository?
Do i always need to use a repository when interacting with the entity framework?
Do i need to create a POCO for each entity?
You should have a plain old CLR object for most entities in your model. You should also have a POCO for each complex type (value object in ddd). Cases where you might not want a POCO for an entity is when creating gerund types for m..n relationships. You can create POCOs for these in EF 4.1, but you don't have to.
Do i ever reference the auto-generated EF classes/entites as attributes of a repository?
The only auto-generated EF classes/entities that I know of in EF 4.1 code first are the dynamic proxies that are created at runtime to populate your navigation and collection properties. You can't and shouldn't try to reference these in any of your source code. Oh, and I think you may be confusing the term "attribute". Attributes are special classes that you can use to decorate classes and methods. Entity classes cannot be used as attributes in this sense.
Do i always need to use a repository when interacting with the entity framework? No. In fact a lot of people say you shouldn't create a repository until you find that you need one. But if you drive your development from unit tests, you will find need for a repository interface quickly.
In Entity Framework, your DataContext class is a repository, and one over which you have a lot of control with EF 4.1. I don't in any way mean to sound flippant, because this is a really good question with a lot of bad answers.
When you use EF, you're already using the repository pattern. Take advantage of that and write less code. Resist the urge to over-architect.
1) This depends on how your behavioral model (your objects) translates to your data model (your database.) There is truly no prescriptive guidance.
2) EF already does this, if by attributes you mean properties.
3) You already do. :-)
Stephen

Is there a performance difference between Model First and Code First in MS Entity Framework 4.1?

I'm starting a new development and I plan to use Code First in Entity Framework 4.1.
I have previously used Model First and found some performance issues around loading context, first calls to SaveChanges() and where Association Fix-up kicks in.
Has anyone compared performance of these two techniques - or, at the end of the day are they insignificant?
Thanks.
I believe that there is no difference at all in performance. Code-First, Model-First, Database-First are modelling strategies at design time. For both Model-First and Database-First entity classes and a DbContext will be created with a T4 template. At runtime EF 4.1 just works with those classes and it doesn't matter where they come from - hand-written (Code-First) or autogenerated from the T4 template (Model-First, Database-First).
Also keep in mind that the benefit that Model-First gives you is rather limited in my opinion: You just have the possibility to create your model classes on a design surface in VS2010. But there are more drawbacks on the other side: The default T4 template isn't very fine granular in creating the code from the model. For instance: It doesn't put MaxLength attributes on the properties, it creates always navigation properties on both sides on a relationship (you often don't want and need both sides) and the overridden OnModelCreating method in DbContext just contains the single line throw new UnintentionalCodeFirstException(); which isn't particularly impressive. You can modify the template and the CSDL part of the EDMX file though to achieve more granularity when the model classes and the DbContext are generated (thanks to Ladislav for his comment below about this option).
In other words it is very likely that you have to tweak the generated code (adding attributes, removing unwished navigation properties, adding Fluent mapping code and so on) in order to get the finetuned model classes you want to work with. As soon as you have done this it becomes difficult to do any changes in the model designer because the DbContext generator will overwrite all your hand-made changes in the code.
In my opinion Model-First with EF 4.1 is only useful if you already have a model designed in the designer surface for instance from an older EF 4.0 project and you want to migrate your project to EF 4.1 In this case the DbContext generator might be useful to create initial code for you. From that point I would proceed with working in the code alone which means: Working with Code-First. If you start with a new project I would prefer Code-First from the beginning. Even if you really want or need this visual representation of the model in the designer surface also in Code-First you can simply create an EDMX file from your DbContext and open it in VS2010 to show your model classes and their relationships in the designer:
using (var context = new MyDbContext())
{
using (var writer = new XmlTextWriter(#"c:\MyModel.edmx", Encoding.Default))
{
EdmxWriter.WriteEdmx(context, writer);
}
}
Edit
There is actually one point where EF 4.1 recogizes the difference whether a model comes from Model-First (i.e. an EDMX model file and designer surface) or if it is a pure Code-First model - and that is the connection string. If you create a model from Model-First you get a connection string which contains references to the model metadata files, like so:
<add name="MyConnectionString"
connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl
|res://*/Model.msl;provider=System.Data.SqlClient;
provider connection string="data source=.\sqlexpress;
initial catalog=MyDb;integrated security=True;
multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
Whereas for Code-First simply a "normal" connection string without metadata references is used:
<add name="MyConnectionString"
connectionString="Server=.\SQLEXPRESS;Database=MyDb;Trusted_Connection=Yes;"
providerName="System.Data.SqlClient" />
Now you can use the second simple connection string without problems also for a model which is created via Model-First. But the code snippet above (creating an EDMX from DbContext) throws an exception with the first connection string telling that WriteEdmx can only be used with Code-First but not Model-First or Database-First. So obviously the DbContext processes or stores somehow the metadata information from the connection string.
How to interprete this? Does it mean that it actually uses the data in the EDMX file specified in the connection string when the model is built in memory? In this case there could theoretically be a performance difference between Code-First and Model-First (at least at model-build-time). But I don't think that the metadata are actually processed. But the mentioned exception is somewhat weird. Why does EF 4.1 prevent me to create an EDMX model file when my model comes from Model-First? Perhaps just to avoid possible confusion and mess with two EDMX files? I don't know.
Yes, there are performance differences between Model First (EF 4.0) and Code First (EF 4.1 - 4.3.1):
You cannot pre-generate internal query views. This means that every time EF tries to run its first query (per app domain), it will need to perform an expensive operation to generate those views, depending on your model complexity. This usually affects application startup performance and can make debugging quite annoying.
You cannot use compiled queries. This can seriously affect queries that are used often, especially complex queries. It can become a serious bottleneck and a CPU hog. Only EF 5.0 (that will be included with .NET 4.5) fixes this issue by automatically compiling all queries, including Code First queries.
According to this benshmark yes. It says also that EF Model First is always faster than EF Code First.

How do I use Entities CTP4 model first and then add data annotations such as validation rules?

I'm creating a model, which is then generating SQL to create the database. Now I have some great entity classes in a single .designer.cs file.
However, I then want to add [Required] to some of the fields that I've created model-first. I've created public partial classes, but I can't redefine the fields to add the [Required] annotation.
Any thoughts?
As far as I can tell so far, with CTP5, this hasn't really changed from plain EF 4; you create partial classes for the entities you need to validate, then use the MetadataTypeAttribute. This is an obnoxious way to do things, but you can read all about it on MSDN here.
CTP 5 also added a T4 generation template that lets you use the model to generate DbContext based classes instead of the more traditional ones from plain EF 4. This is detailed here.. This doesn't change, as far as I can see, the need to use partials and MetadataTypeAttributes.
I'm still hoping for some convergence here, but so far most of the real goodies in the CTPs seem to be going to the Code-First camp which can now use data annotations without any acrobatics. Of course, finding solid info on the CTPs is also a bit hard. The docs there, and the web is polluted with so much noise from previous CTPs that good info is getting very hard to find.

Resources