Is it always better to use 'DbContext' instead of 'ObjectContext'? - dbcontext

I just downloaded EntityFramework.dll v4.3. I've found a number of questions that compare DbContext vs. ObjectContext. But most of these are from 2010, or early 2011.
I'd like to read more on the subject. Specifically, are there any books on DbContext I can get my hands on? I also want to know, as of today, what are the limitations of DbContext when comparing it to its older brother the ObjectContext?
I realize that DbContext is more compact in that it exposes fewer properties. This suggests to me that I should migrate from ObjectContext. But, if I do this migration, will I give up any capabilities? For example, I've read that DbContext doesn't have the STE (Self-tracking entities) capability. Does this still hold true and is it a concern?

I'd like to read more on the subject. Specifically, are there any
books on DbContext I can get my hands on?
Your question does not start off well because a single Google query will give you an answer for this. There is an excellent book about DbContext itself — it doesn't contain anything about the Code First approach, but I guess that is really not the point of your question.
I've found a number of questions that compare DbContext vs.
ObjectContext. But most of these are from 2010, or early 2011.
If you just want to replace ObjectContext + EDMX with DbContext + EDMX, the comparison is still the same. DbContext is a wrapper around ObjectContext and its feature set didn't grow up except with respect to those features related to Code First and Migrations.
I realize that DbContext is more compact in that it exposes fewer
properties. This suggests to me that I should migrate from
ObjectContext.
Yes, it is more compact and it simplifies most common tasks that you have to do with the context. For more complex tasks, you can still convert a DbContext instance to an ObjectContext instance through IObjectContextAdapter.
But, if I do this migration, will I give up any capabilities? For
example, I've read that DbContext doesn't have the STE (Self-tracking
entities) capability. Does this still hold true and is it a concern?
STE was created for ObjectContext and I don't think it was ported to DbContext, but you can try to implement this capability yourself.
STEs are just a template with an idea to solve some problem. It appeared as a good theoretical solution but it wasn't very well accepted by the developer community because the solution is not very good for real world scenarios. It is also the reason why other more important features are being developed instead of improving or porting the template.

Related

Basic Entity Framework Questions

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.

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

One Model to Rule Them All - VS2010 UML, ADO.NET Entity Data Model, and T4

I worked on a fairly large project a while back where we modeled the classes in Enterprise Architect and generated the (partial) POCO classes (complete with model-driven business rule validations), persistence (NHibernate mapping file) and DDL. Based on certain model attributes we could flag alternate generation strategies or indicate that a particular portion would be entirely hand-coded.
There was a good deal of initial investment, but it paid large dividends over the lifetime of a 15 developer, 3 year project.
I'm investigating doing something similar with the current Microsoft technology stack. The place I'm stuck is that class modeling is done with the VS 2010 UML tools, but logical data modeling is done with Entity Data Modeler.
Is it a reasonable path to use VS 2010 UML as the "single source of truth" and code generate the edmx files based on the class model? That's the inverse of the common path to create the entity model and use a POCO generator to generate classes. However, a good class model can be used to generate much more than just the properties so I tend to view it as a better choice than the entity model.
Entity Data Modeler is limited to a single diagram per model and becomes unusable in non-trivial scenarios. You can use UML profiles to extend class models for logical data modeling. It requires a significant investment of effort and time which may be justified on a 3-year 15-developer project.
It's always going to be a problem, as each modeling layer maps two disparate worlds. To have fully aware code, your generation system must have access to all mapping models. IOW, you can't simply declare one to be the "master", as each layer is a "real" perspective of the solution.
Yes, this is possible. No, there is nothing built in. To do this you'd need to write a VSIX which would consume the model and emit EDMX/code. This isn't necessarily hard, but you'd have to do it yourself. You'd also need a pattern or attributes for handling the modeling aspects which you might not have in your diagrams, just like you have to do for specifying key fields and the like when doing code-first modeling.

Persistence framework?

I'm trying to decide on the best strategy for accessing the database. I understand that this is a generic question and there's no a single good answer, but I will provide some guidelines on what I'm looking for.
The last few years we have been using our own persistence framework, that although limited has served as well. However it needs some major improvements and I'm wondering if I should go that way or use one of the existing frameworks. The criteria that I'm looking for, in order of importance are:
Client code should work with clean objects, width no database knowledge. When using our custom framework the client code looks like:
SessionManager session = new SessionManager();
Order order = session.CreateEntity();
order.Date = DateTime.Now;
// Set other properties
OrderDetail detail = order.AddOrderDetail();
detail.Product = product;
// Other properties
// Commit all changes now
session.Commit();
Should as simple as possible and not "too flexible". We need a single way to do most things.
Should have good support for object-oriented programming. Should handle one-to-many and many-to-many relations, should handle inheritance, support for lazy loading.
Configuration is preferred to be XML based.
With my current knowledge I see these options:
Improve our current framework - Problem is that it needs a good deal of effort.
ADO.NET Entity Framework - Don't have a good understanding, but seems too complicated and has bad reviews.
LINQ to SQL - Does not have good handling of object-oriented practices.
nHibernate - Seems a good option, but some users report too many archaic errors.
SubSonic - From a short introduction, it seems too flexible. I do not want that.
What will you suggest?
EDIT:
Thank you Craig for the elaborate answer. I think it will help more if I give more details about our custom framework. I'm looking for something similar. This is how our custom framework works:
It is based on DataSets, so the first thing you do is configure the
DataSets and write queries you need there.
You create a XML configuration file that specifies how DataSet tables map to objects and also specify associations between them (support for all types of associations).
3.A custom tool parse the XML configuration and generate the necessary code.
4.Generated classes inherit from a common base class.
To be compatible with our framework the database must meet these criteria:
Each table should have a single column as primary key.
All tables must have a primary key of the same data type generated on the
client.
To handle inheritance only single table inheritance is supported. Also the XML file, almost always offers a single way to achieve something.
What we want to support now is:
Remove the dependency from DataSets. SQL code should be generated automatically but the framework should NOT generate the schema. I want to manually control the DB schema.
More robust support for inheritance hierarchies.
Optional integration with LINQ.
I hope it is clearer now what I'm looking for.
Improve our current framework - Problem is that it needs a good deal of effort
In your question, you have not given a reason why you should rewrite functionality which is available from so many other places. I would suggest that reinventing an ORM is not a good use of your time, unless you have unique needs for the ORM which you have not specified in your question.
ADO.NET Entity Framework
We are using the Entity Framework in the real world, production software. Complicated? No more so than most other ORMs as far as I can tell, which is to say, "fairly complicated." However, it is relatively new, and as such there is less community experience and documentation than something like NHibernate. So the lack of documentation may well make it seem more complicated.
The Entity Framework and NHibernate take distinctly different approaches to the problem of bridging the object-relational divide. I've written about that in a good bit more detail in this blog post. You should consider which approach makes the most sense to you.
There has been a great deal of commentary about the Entity Framework, both positive and negative. Some of it is well-founded, and some of the seems to come from people who are pushing other solutions. The well-founded criticisms include
Lack of POCO support. This is not an issue for some applications, it is an issue for others. POCO support will likely be added in a future release, but today, the best the Entity Framework can offer is IPOCO.
A monolithic mapping file. This hasn't been a big issue for us, since our metadata is not in constant flux.
However, some of the criticisms seem to me to miss the forest for the trees. That is, they talk about features other than the essential functionality of object relational mapping, which the Entity Framework has proven to us to do very well.
LINQ to SQL - Does not have good handling of object-oriented practices
I agree. I also don't like the SQL Server focus.
nHibernate - Seems a good option, but some users report too many archaic errors.
Well, the nice thing about NHibernate is that there is a very vibrant community around it, and when you do encounter those esoteric errors (and believe me, the Entity Framework also has its share of esoteric errors; it seems to come with the territory) you can often find solutions very easily. That said, I don't have a lot of personal experience with NHibernate beyond the evaluation we did which led to us choosing the Entity Framework, so I'm going to let other people with more direct experience comment on this.
SubSonic - From a short introduction, it seems too flexible. I do not want that.
SubSonic is, of course, much more than just an ORM, and SubSonic users have the option of choosing a different ORM implementation instead of using SubSonic's ActiveRecord. As a web application framework, I would consider it. However, its ORM feature is not its raison d'être, and I think it's reasonable to suspect that the ORM portion of SubSonic will get less attention than the dedicated ORM frameworks do.
LLBLGen make very good ORM tool which will do almost all of what you need.
iBATIS is my favourite because you get a better grain of control over the SQL
Developer Express Persistence Objects or XPO as it is most known. I use it for 3 years. It provides everything you need, except that it is commercial and you tie yourself with another (single company) for your development. Other than that, Developer Express is one of the best component and framework providers for the .NET platform.
An example of XPO code would be:
using (UnitOfWork uow = new UnitOfWork())
{
Order order = new Order(uow);
order.Date = DateTime.Now();
uow.CommitChanges();
}
I suggest taking a look at the ActiveRecord from Castle
I don't have production experience with it, I've just played around with their sample app. It seems really easy to work with, but I don't know it well enough to know if it fits all your requirements

What would you choose for your data layer today, Linq or Subsonic?

We are ready to start a brand new project at work, no legacy code. We did use Subsonic in the past and we pretty happy with it. But that was before Linq.
Has anyone had to face this same issue (Linq x Subsonic)?
What was your decision? What were the reasons?
Any insight appreciated.
SubSonic
Pros:
Nice and simple
Scaffolding
Cons:
Method signatures often accept string parms (though you're encouraged to use DAO string constants) which can be abused.
Keep in mind:
Requires Website project for no-code, hands-off model generation (needs the BuildProvider).
Linq To SQL
Pros:
Syntactic sugar in the IDE
MS supported
View the SQL to be executed in the IDE
Allows different levels of fiddling in the model, from auto-generation to explicit definitions down to object properties.
Cons:
Complex. You need to learn new concepts like the DataContext to be effective.
Keep in mind:
Some stackoverflow users question Linq to SQL's continued support.
Also evaluate the ADO.NET Entity Framework and here.
The one thing I love about LINQ, which I don't think SubSonic handles as gracefully, is automatically dealing with joins.
FROM a in db.Orders
where a.Total > 100
SELECT new {a.Item.Desc, a.Customer.Name};
will automatically generate SQL like thisL
select i.DESC, c.NAME
from ORDERS o
inner join ITEMS on o.ItemID = i.ItemID
inner join CUSTOMERS c on o.CustomerID = c.CUSTOMERID
where o.TOTAL > 100
What about NHibernate? Is it really out of the picture for new projects? Still, people coming from Java will find it familiar and you can also use it with .NET 2.0 and Mono.
I went with Linq because it's built into the framework. For those saying it will not be supported by Microsoft... it's LinqToSql that is going to be phased out. I believe one of the plans is to absorbe it into the Entity Framework.
I'm now using the Entity Framework. It also uses linq and basically it's exactly like linqToSql with more flexibility and power if you choose to use it.
I tend to avoid 3rd party frameworks and orms because eventually they die out as well. I believe they have more of a chance to die out because their life comes from how many people are interested in it and use it. Their life is also heavily dependent on it's main author/contributor.
My experience has been primary with SubSonic. It is very straight forward to deploy and you'll have your DAL completed in under a half hour. Bear in mind that this is a Swiss Army knife, as it is designed for utility. Basically you get a class generated per table, as well as the ability to peform lazy loading for collections. You can also execute stored procedures via the framework, so if you have complex data structures you can fetch them from the database and update a class that you hand craft.
I've used it on 5 major projects now, and am impressed with how quickly I became dependent on it.
I was in the same situation. LinQ is more "Visual", you do everything inside vstudio, and even Rob admits subsonic have a few things to match it.
IEnumerable, LINQDatasource ( with auto paging) and the visual modeling have convinced me to choose Linq over Subsonic.
The biggest risk with linq to sql is that Microsoft will grow tired of it and abandon it. There is a lot of speculation that this has already happened and that only the entity framework will be updated. Subsonic does not suffer from this and worse case you have the source code to make your edits.
You might want to look into what happens when MS stops developing LINQ to SQL,as it appears to be happening. SubSonics latest version is easier to create queries and more readable, then their previous version.

Resources