Announcing Entity Framework Code-First (CTP5 release)

This week the data team released the CTP5 build of the new Entity Framework Code-First library.  EF Code-First enables a pretty sweet code-centric development workflow for working with data.  It enables you to:

  • Develop without ever having to open a designer or define an XML mapping file
  • Define model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping

I’m a big fan of the EF Code-First approach, and wrote several blog posts about it this summer:

Today’s new CTP5 release delivers several nice improvements over the CTP4 build, and will be the last preview build of Code First before the final release of it.  We will ship the final EF Code First release in the first quarter of next year (Q1 of 2011).  It works with all .NET application types (including both ASP.NET Web Forms and ASP.NET MVC projects).

Installing EF Code First

You can install and use EF Code First CTP5 using one of two ways:

Approach 1) By downloading and running a setup program.  Once installed you can reference the EntityFramework.dll assembly it provides within your projects.

     or:

Approach 2) By using the NuGet Package Manager within Visual Studio to download and install EF Code First within a project.  To do this, simply bring up the NuGet Package Manager Console within Visual Studio (View->Other Windows->Package Manager Console) and type “Install-Package EFCodeFirst”:

image

Typing “Install-Package EFCodeFirst” within the Package Manager Console will cause NuGet to download the EF Code First package, and add it to your current project:

image

Doing this will automatically add a reference to the EntityFramework.dll assembly to your project:

image 

NuGet enables you to have EF Code First setup and ready to use within seconds.  When the final release of EF Code First ships you’ll also be able to just type “Update-Package EFCodeFirst” to update your existing projects to use the final release.

EF Code First Assembly and Namespace

The CTP5 release of EF Code First has an updated assembly name, and new .NET namespace:

  • Assembly Name: EntityFramework.dll
  • Namespace: System.Data.Entity

These names match what we plan to use for the final release of the library.

Nice New CTP5 Improvements

The new CTP5 release of EF Code First contains a bunch of nice improvements and refinements. Some of the highlights include:

  • Better support for Existing Databases
  • Built-in Model-Level Validation and DataAnnotation Support
  • Fluent API Improvements
  • Pluggable Conventions Support
  • New Change Tracking API
  • Improved Concurrency Conflict Resolution
  • Raw SQL Query/Command Support

The rest of this blog post contains some more details about a few of the above changes.

Better Support for Existing Databases

EF Code First makes it really easy to create model layers that work against existing databases.  CTP5 includes some refinements that further streamline the developer workflow for this scenario.

Below are the steps to use EF Code First to create a model layer for the Northwind sample database:

Step 1: Create Model Classes and a DbContext class

Below is all of the code necessary to implement a simple model layer using EF Code First that goes against the Northwind database:

image

EF Code First enables you to use “POCO” – Plain Old CLR Objects – to represent entities within a database.  This means that you do not need to derive model classes from a base class, nor implement any interfaces or data persistence attributes on them.  This enables the model classes to be kept clean, easily testable, and “persistence ignorant”.  The Product and Category classes above are examples of POCO model classes.

EF Code First enables you to easily connect your POCO model classes to a database by creating a “DbContext” class that exposes public properties that map to the tables within a database.  The Northwind class above illustrates how this can be done.  It is mapping our Product and Category classes to the “Products” and “Categories” tables within the database.  The properties within the Product and Category classes in turn map to the columns within the Products and Categories tables – and each instance of a Product/Category object maps to a row within the tables.

The above code is all of the code required to create our model and data access layer!  Previous CTPs of EF Code First required an additional step to work against existing databases (a call to Database.Initializer<Northwind>(null) to tell EF Code First to not create the database) – this step is no longer required with the CTP5 release. 

Step 2: Configure the Database Connection String

We’ve written all of the code we need to write to define our model layer.  Our last step before we use it will be to setup a connection-string that connects it with our database.  To do this we’ll add a “Northwind” connection-string to our web.config file (or App.Config for client apps) like so:

  <connectionStrings>
     
    <add name="Northwind"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\northwind.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />

  </connectionStrings>

EF “code first” uses a convention where DbContext classes by default look for a connection-string that has the same name as the context class.  Because our DbContext class is called “Northwind” it by default looks for a “Northwind” connection-string to use.  Above our Northwind connection-string is configured to use a local SQL Express database (stored within the \App_Data directory of our project).  You can alternatively point it at a remote SQL Server.

Step 3: Using our Northwind Model Layer

We can now easily query and update our database using the strongly-typed model layer we just built with EF Code First.

The code example below demonstrates how to use LINQ to query for products within a specific product category.  This query returns back a sequence of strongly-typed Product objects that match the search criteria:

image

The code example below demonstrates how we can retrieve a specific Product object, update two of its properties, and then save the changes back to the database:

image

EF Code First handles all of the change-tracking and data persistence work for us, and allows us to focus on our application and business logic as opposed to having to worry about data access plumbing.

Built-in Model Validation

EF Code First allows you to use any validation approach you want when implementing business rules with your model layer.  This enables a great deal of flexibility and power.

Starting with this week’s CTP5 release, EF Code First also now includes built-in support for both the DataAnnotation and IValidatorObject validation support built-into .NET 4.  This enables you to easily implement validation rules on your models, and have these rules automatically be enforced by EF Code First whenever you save your model layer.  It provides a very convenient “out of the box” way to enable validation within your applications.

Applying DataAnnotations to our Northwind Model

The code example below demonstrates how we could add some declarative validation rules to two of the properties of our “Product” model:

image

We are using the [Required] and [Range] attributes above.  These validation attributes live within the System.ComponentModel.DataAnnotations namespace that is built-into .NET 4, and can be used independently of EF.  The error messages specified on them can either be explicitly defined (like above) – or retrieved from resource files (which makes localizing applications easy).

Validation Enforcement on SaveChanges()

EF Code-First (starting with CTP5) now automatically applies and enforces DataAnnotation rules when a model object is updated or saved.  You do not need to write any code to enforce this – this support is now enabled by default. 

This new support means that the below code – which violates our above rules – will automatically throw an exception when we call the “SaveChanges()” method on our Northwind DbContext:

image

The DbEntityValidationException that is raised when the SaveChanges() method is invoked contains a “EntityValidationErrors” property that you can use to retrieve the list of all validation errors that occurred when the model was trying to save.  This enables you to easily guide the user on how to fix them.  Note that EF Code-First will abort the entire transaction of changes if a validation rule is violated – ensuring that our database is always kept in a valid, consistent state.

EF Code First’s validation enforcement works both for the built-in .NET DataAnnotation attributes (like Required, Range, RegularExpression, StringLength, etc), as well as for any custom validation rule you create by sub-classing the System.ComponentModel.DataAnnotations.ValidationAttribute base class.

UI Validation Support

A lot of our UI frameworks in .NET also provide support for DataAnnotation-based validation rules. For example, ASP.NET MVC, ASP.NET Dynamic Data, and Silverlight (via WCF RIA Services) all provide support for displaying client-side validation UI that honor the DataAnnotation rules applied to model objects.

The screen-shot below demonstrates how using the default “Add-View” scaffold template within an ASP.NET MVC 3 application will cause appropriate validation error messages to be displayed if appropriate values are not provided:

image

ASP.NET MVC 3 supports both client-side and server-side enforcement of these validation rules.  The error messages displayed are automatically picked up from the declarative validation attributes – eliminating the need for you to write any custom code to display them.

Keeping things DRY

The “DRY Principle” stands for “Do Not Repeat Yourself”, and is a best practice that recommends that you avoid duplicating logic/configuration/code in multiple places across your application, and instead specify it only once and have it apply everywhere.

EF Code First CTP5 now enables you to apply declarative DataAnnotation validations on your model classes (and specify them only once) and then have the validation logic be enforced (and corresponding error messages displayed) across all applications scenarios – including within controllers, views, client-side scripts, and for any custom code that updates and manipulates model classes.

This makes it much easier to build good applications with clean code, and to build applications that can rapidly iterate and evolve.

Other EF Code First Improvements New to CTP5

EF Code First CTP5 includes a bunch of other improvements as well.  Below are a few short descriptions of some of them:

  • Fluent API Improvements

EF Code First allows you to override an “OnModelCreating()” method on the DbContext class to further refine/override the schema mapping rules used to map model classes to underlying database schema.  CTP5 includes some refinements to the ModelBuilder class that is passed to this method which can make defining mapping rules cleaner and more concise.  The ADO.NET Team blogged some samples of how to do this here.

  • Pluggable Conventions Support

EF Code First CTP5 provides new support that allows you to override the “default conventions” that EF Code First honors, and optionally replace them with your own set of conventions.

  • New Change Tracking API

EF Code First CTP5 exposes a new set of change tracking information that enables you to access Original, Current & Stored values, and State (e.g. Added, Unchanged, Modified, Deleted).  This support is useful in a variety of scenarios.

  • Improved Concurrency Conflict Resolution

EF Code First CTP5 provides better exception messages that allow access to the affected object instance and the ability to resolve conflicts using current, original and database values. 

  • Raw SQL Query/Command Support

EF Code First CTP5 now allows raw SQL queries and commands (including SPROCs) to be executed via the SqlQuery and SqlCommand methods exposed off of the DbContext.Database property.  The results of these method calls can be materialized into object instances that can be optionally change-tracked by the DbContext.  This is useful for a variety of advanced scenarios.

  • Full Data Annotations Support

EF Code First CTP5 now supports all standard DataAnnotations within .NET, and can use them both to perform validation as well as to automatically create the appropriate database schema when EF Code First is used in a database creation scenario. 

Summary

EF Code First provides an elegant and powerful way to work with data.  I really like it because it is extremely clean and supports best practices, while also enabling solutions to be implemented very, very rapidly.  The code-only approach of the library means that model layers end up being flexible and easy to customize.

This week’s CTP5 release further refines EF Code First and helps ensure that it will be really sweet when it ships early next year.  I recommend using NuGet to install and give it a try today.  I think you’ll be pleasantly surprised by how awesome it is.

Hope this helps,

Scott

119 Comments

  • cool it's really helpfull

  • Feed may have an issue

    PM> Install-Package EFCodeFirst
    Install-Package : Object reference not set to an instance of an object.
    At line:1 char:16
    + Install-Package <<<< EFCodeFirst
    + CategoryInfo : NotSpecified: (:) [Install-Package], NullReferenceException
    + FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

  • Is the code first approach supported by RIA Services?

  • What's the recommended method to add a Category Dropdown to the view in your example?

  • Fantastic work guys - I really love this code first approach. Can't wait to get stuck into it.

  • Nice to see that it is progressing to the right direction, there are two more features, I would like to mention:

    1. When creating the database from Model or script it does not take order of declaration into consideration when creating the table, instead it creates the tables in ascending order of the property names. The same is true for joining table of a many to many relationship.

    2. When relationship is defined it should automatically create index for the foreign key column.

    Thanks.

  • Is still mapping enum types not supported by EF even in CTP5?
    Do the team has a plans to support enum mapping in future releases?

  • @Hurricanepkt

    Are you using CTP1 still? That error message comes from the fact that older packages are installed (the package format changed).

  • @Igorbek Enum support need to be implemented at EF Core.

    I asked about this way of releases above

  • "It works with all .NET application type"

    Will work with WCF RIA Domain Services?


  • Hurray! After so many years EF at last becomes L2S!
    Long live LINQ TO SQL!

  • Hi Scott,
    Thanks alot! Your blog-entry always provide very good start to adapt newest things...

    Had a query about it, How silverlight client can utilize validation framework of EF? Any pointer/link would be great help.

  • Anyway to easily localize those annotations messages, while keeping this nice syntax with the system default (English) in place?

  • Hi Scott

    DataContext, EntityContext, ObjectContext... Do we have to another xxContext. Couldn't we just do this as an on/off option in ObjectContext (much the same was as we have generate proxies as an option?) Maybe even a special mapping source that just plugs into EF4 [though someone will probably tell that is what it does anyway... please don't... :) ]

  • Hello,

    Awesome work guys! I can't wait to see this released (RTM). I'm working on a set of Entity Framework templates for CodeSmith and am always glad to see new content on this subject :).

    Thanks
    -Blake Niemyjski

  • One more thing forgot to mention, any plan to include Rails Active Record Like migration feature?

  • How does it work with other databases ?

  • This is sweet!

    @Scott: If you setup a read only property for say a "CreateDate" field that your database populates for you, does the SaveChanges automatically ignore this on saving or do you need to override the method to handle this ?

  • Nice. I also would like to see support for SP mapping in the final release.

  • Nice work! I'm wondering if you guys are planning to add support for sql_variant in the final version - that's what's holding up our migration from LinqToSql to EF.

  • I previously read about support for mapping to existing SPROCs. What is the status? Is it going to make EF4 Code-first before RTM?

    Thanks.

  • Is there a way to have code called on an object when that object is inserted, updated, or deleted in the database.

  • Some explicit instructions on how to convert CTP4 code to CTP5 code are needed,

  • How do I update my Package Manager Console??? I sill have to use Add-Package and I am not seeing all the packages????

  • Scott
    I like the idea of data annotations on class properties over using fluent configuration. The trouble is that if you have too many rules it can obscure the structure and function of the class. Would it be possible to give the Visual Studio UI the ability to toggle attribute visibility on and off leaving some sort of placeholder?

    Also, does this CTP contain T4 template generation? I had heard that was in the works.

  • Scott,

    How can this be done in the CTP5:

    modelBuilder.Entity()
    .MapHierarchy()
    .Case(b => new { b.Id, b.Comment, Discriminator = 0 })
    .Case(s => new { request1_Id = Column.Id, Discriminator = 1 })
    .Case(m => new { request2_Id = Mission.Id, m.Comment, m.Date, Discriminator = 2 })
    .ToTable("dbo.Requests");

  • @Roland: Code First is part of EF so uses the same EF database provider model. To use Code First with other databases give it a connection string to your DB and you should be OK.

    @willc: The CTP contains T4 templates so you can change the code generation for EDMX models to use the simplified EF data access API, i.e. DbContext and DbSet.

    @NaZAf: How critical is stored proc support for your shop. I'd appreciate hearing how/where you use stored procs (e.g. for all CRUD or just special cases). Can you email me (timlav@microsoft.com).


  • // inside Product class, I incorrectly coded this:
    public string CategoryID { get; set;} // wrong - should be int - my initial oversight.

    // However, this code works but should not because the 'model' is obviously incorrect
    // compared to the actual Northwind database schema.
    // Code from class NorthwindDatabaseInitializer : IDatabaeInitializer
    public void InitializeDatabase(Northwind context)
    {
    if (context.Database.Exists() && context.Database.CompatibleWithModel(false))
    {
    Console.WriteLine("Database exists and is compatible with our model");
    }
    else
    {
    Console.WriteLine("Database exists but is not compatible with our model");
    }
    }

    I always see the message "Database exists and is compatible with our model", which is wrong.

  • I haven't played with EF, so this may be a naive question, but why is there a CategoryID on the Product? Isn't that redundant? Who is responsible for setting it?

    Thanks!

  • When generating the database in a model-first scenario, does CTP5 allow modification of tables, or does it still drop all of the tables before re-adding them?

  • Still cant get Code-First to create a SQL database in a specific directory (specify either full path for WPF app or |DataDirectory|\... for asp.net app_data dir in the connection string).

    Get error "Cannot open database for 'FootballDB' requested by the login. The login failed. Login failed for {MyUserName}"

    Works fine for SQL CE and SQL Express to the default SQL Data directory.

    Was getting this error in CTP4, hoping it was fixed in CTP5, but no dice.

    Any thoughts?

  • @timlav - many thanks, Tim. Evolution would be fantastic. It's so painful when having to make minor changes to schema during development. How do you guys/everyone else get around this at the moment?

  • @Hurricanepkt

    >>>>> Feed may have an issue PM> Install-Package EFCodeFirst Install-Package : Object reference not set to an instance of an object.

    Can you check that you have the latest version of NuGet installed? That error seems to indicate that you might have the first CTP version of it. Can you go to the Extension Manager within Visual Studio and update it and try again?

    Thanks,

    Scott

  • @sirdemon

    >>>>>> Is the code first approach supported by RIA Services?

    We are working to add support for it. I believe currently you have to write some extra code to enable it though.

    Hope this helps,

    Scott

  • @Jonas,

    >>>>>> What's the recommended method to add a Category Dropdown to the view in your example?

    I'm planning on doing a blog post to cover this scenario soon. Basically you want to do two things:

    1) Within your controller create a SelectList() object and pass it your list of category objects. Indicate with the SelectList which property represents the value and text on the category. Then pass it to the View using ViewData.

    For example:

    public ActionResult Edit(int id) {

    ViewData["categories"] = new SelectList(northwind.Categories.ToList(),"CategoryID", "CategoryName");

    var product = northwind.Products.Find(id);

    return View(product);
    }

    Then within your view have the Category be displayed via this code:


    @Html.LabelFor(model => model.CategoryID)


    @Html.DropDownListFor(model => model.CategoryID, (ViewData["categories"] as SelectList))
    @Html.ValidationMessageFor(model => model.CategoryID)


    Hope this helps,

    Scott

  • @Kazi,

    >>>>>> Nice to see that it is progressing to the right direction, there are two more features, I would like to mention:

    >>>>>> 1. When creating the database from Model or script it does not take order of declaration into consideration when creating the table, instead it creates the tables in ascending order of the property names. The same is true for joining table of a many to many relationship.

    >>>>>> 2. When relationship is defined it should automatically create index for the foreign key column.

    Thanks for the suggestions! I forwarded them along to the data team.

    Thanks,

    Scott

  • @Igorbek

    >>>>>> Is still mapping enum types not supported by EF even in CTP5? Do the team has a plans to support enum mapping in future releases?

    The unfortunately won't be supported with the initial EF Code First release. EF4 doesn't yet support enums, and EF Code First is built on EF4 and so doesn't either. The data team is looking to add this support to the next release to the EF base though.

    Hope this helps,

    Scott

  • @Fujiy

    >>>>> Can we expected entity framework standalone of .net framework? Entity Framework is always released together .Net Framework. This is a problem, if you need features of EF 4.0, but using .NET 3.5 SP1.

    EF Code First will ship as a separate library (and can be installable via NuGet). It will require, though, .NET 4 as it builds on top of EF4.

    Hope this helps,

    Scott

  • @Sutikshan dubey

    >>>>>> Had a query about it, How silverlight client can utilize validation framework of EF? Any pointer/link would be great help.

    WCF RIA Services provides support for this. You should be able to find some good tutorials on WCF RIA Services on www.silverlight.net

    Hope this helps,

    Scott

  • @Jon,

    >>>>>>> First we we told that Linq to Entities was the future of DB access for .NET. But then it wasn't ready on time, so we got Linq to SQL instead. We were told that was the way to go, until the Entity Framework was ready, at which point it would be obsolete. Except when the Entity Framework did arrive it sucked, but were told the version with .NET 4.0 would fix things. Now we .NET 4.0 is here, we're told there's still major performance problems ( blogs.msdn.com/.../performance-considerations-when-using-tpt-table-per-type-inheritance-in-the-entity-framework.aspx ) and we're getting a whole different syntax in a future release. At this point, I'm beyond bewildered was to how, when, and where to use the Entity Framework.

    Sorry for the confusion Jon - there have certainly been a lot of options the last few years.

    EF Code First builds on the core EF4 bits that we shipped in .NET 4. Part of the goal with it was to enable entities to be "POCO" (plain old CLR objectS), and not require any custom base classes or data persistence attributes. This is less of a syntax change from EF4, and more a reduction of the properties and OM that is exposed - leaving just the properties and associations that you need to work with. The query syntax used with EF Code First - LINQ - is also the same as in core EF4 (and with LINQ to SQL).

    I believe the data team is pretty locked on EF for the future, and are hard at work evolving and enhancing it. Hopefully all data investments going forward build on top of this core data stack.

    Hope this helps,

    Scott

  • @D. Lambert

    >>>>>>> Thanks for the update, Scott. I'm really happy to see advances in validation for this release. This is one of the areas that's been keeping EF from being an effective "whole model" solution for domains larger than demo scenarios. I haven't seen anything showing support for class-level validation methods (complex validation working across multiple properties) in Code First -- I don't suppose this is hiding in the CTP somewhere, is it? Specifically, I'd like to see something like an OnValidate() method that would be called automatically on entity validation during SaveChanges().

    You can implement the IValidatableObject interface on your models and override the Validate() method it provides. EF Code First will then call this method when SaveChanges() is invoked on the context to verify that the model is valid. Within this Validate() method you can perform any class-level validation you want (including rules that span multiple properties).

    I have a code-sample that shows how to implement IValidatableObject here: http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx

    I'm also going to try and blog more details about it in the future.

    Hope this helps,

    Scott

  • @Sergey

    The initial Code First release will not include support for sql_variant. This is a feature that is on our list for new data types that we'd add to the full Entity Framework stack (Code First sits on top of this). Unfortunately at this time, there aren't any workarounds is you heavily rely on this type.

  • @Kazi

    1. Re: column ordering
    >> Column ordering for properties generally follows reflection order, which is not guaranteed to be the same as the order you declared them but in practice this is almost always the case. You can customize the order by using the ColumnAttribute data annotation on each property. For join tables, you are correct that this cannot always be specified an dI will open an issue to track to make sure you can do this kind of ordering for the join table. For now, if you have a navigation property on both sides, you can do the following to order the columns (left key is the first column, right key is the second column):

    modelBuilder.Entity()
    .HasMany(e => e.Territories)
    .WithMany(t => t.Employees)
    .Map( mm =>
    {
    mm.MapLeftKey(e => e.EmployeeID, "EID");
    mm.MapRightKey(t => t.TerritoryID, "TID");
    });

    2. Re: when a relationship is defined it should automatically create index for the foreign key column.
    >> We recognize this deficiency in the SQL that is generated during database creation and this will be fixed when we rev the SQL Server provider that is part of the full Entity Framework stack.

  • Hi Scott,

    "We will ship the final EF Code First release in the first quarter of next year (Q1 of 2011)."

    Can I assume you are referring to RTW/RTM or are you referring to the final CTP?

    I've just upgraded from CTP4 and I really like the direction this add-on is taking EF.

    Thanks,
    Matt

  • @Jon : hahaha ... That's so right.

  • Hi Scott,
    is there a way to use EF Code First POCO model "metadata" to create custom output? What I am after is a capability to get the model description as EF sees it and then use that to generate some files (pasing it to custom T4 template provider) but without worrying about what property holds primary key or any other convenition (implicit or not). Essentialy, I would be able to just query all model entities, primary keys for each entity, associations etc. Thanks

  • Hello Scott

    When do you plan to implement inheritance in the Entity Framework Code-First? (Table-per-type, Table-per-Hierarchy and Table-per-Concrete-Type)

  • A big problem is serialzing entities because they end up using the proxies instead. It would be handy if our poco classes could control this by adding an attribute like [ScriptIgnore] to prevent lazy loaded child collections going along for the ride. Another problem this would allow us to easily solve is the circular references when trying to serialize. Or, if there was an easy way to convert between proxied objects and simple poco objects for serialization that would be another solution.

  • Hey Scott,

    Great article unforunately Foxpro was still more efficent and has better performance in most scenarios !

    While you have VFP installed check out the class browser it actually does stuff visually like UI control inheritance, pretty cool tool actually.

    Mark


  • @scottgu

    Correcting my question:

    Can we expected entity framework CORE standalone of .net framework? Entity Framework is always released together .Net Framework. This is a problem, if you need features of EF 4.0, but using .NET 3.5 SP1.
    Or about Enum support, that need EF Core update

  • Very nice work!
    However, for validation, do you support also IDataErrorInfo ?

  • Scott,
    What's the approach for creating a new Northwind object (i.e. a new dbContext)? I suppose this is a quite expensive process and we should therefore look best practices for it: singletons, on application start up, unit of work? You get the idea ...
    Thanks,
    Andre.

  • hey scott you have IValidatableObject referenced as IvalidatorObject in your post.

  • hi Scott ,

    i am seriously having a strange problem regarding a LinQ query posting some of the small codes. please tell me where hav i went wrong.




    the POCO class :

    public class Person
    {
    public String ID { get; set; }
    public String Name { get; set; }
    public int Age { get; set; }
    public String Address { get; set; }
    }

    public class personDbContext : DbContext
    {
    public DbSet PersonDetails{ get; set; }
    }
    The query :

    personDbContext storeDB = new personDbContext();
    var list = storeDB.PersonDetails.Select(p=> new
    {
    Personid = p.ID,
    p.Name,
    p.Age,
    p.Address,
    }).ToList();

    Grid.ItemsSource = list.ToList();

    Its Givin inner Exception as :
    {"Invalid object name 'dbo.People'."}

    where as the Table name in DB is "Person" there is no way there are any objects named as people.. can u fix whts d problem with it ... the four fields of table are id , name , age , address..

    i m pretty newbie experimenting this .... please pardon me if i hav made some mistake...

    Regards
    Joy

  • Update :
    more interestingly it is generating the sql as + base {SELECT
    [Extent1].[id] AS [id],
    [Extent1].[name] AS [name],
    [Extent1].[age] AS [age],
    [Extent1].[address] AS [address]
    FROM [dbo].[People] AS [Extent1]} System.Data.Entity.Infrastructure.DbQuery {System.Data.Entity.DbSet}

    whereas the Database and the POCO class both are Person !!!!

    please tel me how is it responsible for generating dbo.People!!!

  • code snippets for above problem :




    POCO Class :
    public class Person
    {
    public String id { get; set; }
    public String name { get; set; }
    public int age { get; set; }
    public String address { get; set; }
    }
    public class personDbContext : DbContext
    {
    public DbSet PersonDetails{ get; set; }
    }

    Linq query : personDbContext storeDB = new personDbContext();
    var list = storeDB.PersonDetails.Select(p=> new
    {
    Personid = p.id,
    p.name,
    p.age,
    p.address,
    }).ToList();

    Grid.ItemsSource = list.ToList();

  • Is there a change tracking api usage or documentation for the new EF4 CTP5?

    My scenarios are two specifically:

    1. Audit purposes - saving old and new values

    2. record versioning - being able to roll-back to specific version of tables (these may span across related objects). For example changes the child records would trigger a revision in any parent records to map to the new values of the child.

    thanks,

  • Does anyone know if "ordered lists" are supported? i.e. where an index column is added to the table and the order is preserved? For example, in the example above Category.Products is of type ICollection, therefore the order is unspecified. I noticed that replacing ICollection with IList works also. Theoretically, if you are using IList the order should be preserved. ORMs like NHibernate let you do this. Any chance that this is or will be supported in EF Code First?

    Also, I'm wondering if there is an equivalent to NHibernate Interceptors. NHibernate Interceptors allow you to receive an event when an object is being saved. I've found this useful in the past for creating an audit interceptor that sets the current user name and time for the object before it is serialized to the database.

    It would also be great if an event were raised after an object was saved, so that you could implement logging. i.e. write out an audit log event stating an object was saved, by who, when, etc.

    I too would very much like to see support for enums.

  • @Scott -
    Received the following when I tried the package manager which I'm guessing is something with my install. Also, I did update NuGet before I tried running this. Thanks.

    Install-Package : The 'minVersion' attribute is not declared.
    At line:1 char:16
    + Install-Package <<<< EFCodeFirst
    + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

  • Also, I would like to see support for classes that have properties like IList. i.e. collections of primitive types. NHibernate binary serializes something like this into a SQL BLOB field. I think that this is something that should be supported, if it is supposed to be persistence ignorant.

  • I'd like a CreateTablesIfNotExists initializer. I already have a database.

  • I think the biggest problem with code-first-with-EF is if you want to use a base class or an interface (like IProduct) you get in deeep troubles. If you keep all objects simple you probably safe.

  • I tried using the EnumDataTypeAttribute but that doesn't seem to work. It always gets the value 0. Has anyone else managed to map to enums?

  • I am getting error :
    System.Data.Edm.EdmEntityType: : EntityType 'Customers' has no key defined. Define the key for this EntityType.
    System.Data.Edm.EdmEntitySet: EntityType: The EntitySet Customers is based on type Customers that has no keys defined.

    My code is :
    var customers = from c in n.Customers
    where c.Companyname.StartsWith("A")
    select c;

    As far as I know, my mapping of the Northwind Customers table is just like in your example.

    Thanks in advance,
    Brian

  • System.Data.Entity.Infrastructure.Database.SetInitializer.... is now
    System.Data.Entity.Infrastructure.DbDatabase.SetInitializer; Is that correct?

    Where is this best accomplished??? App start in Global.asax or override OnModelCreating in Dbcontext?

    Great stuff. Thanks.

  • Are there any issues with EditorFor templates in the EditorTemplates folder with CTP 5 Code First? Worked fine with MVC 2 but can't get them to render either with datatype or UI Hint.

  • Is the Package Manager supposed to add the files to the FIRST project in the solution. Selecting a project and even marking it as startup project seems to have no effect.

  • @Chris,

    >>>>>>> If you setup a read only property for say a "CreateDate" field that your database populates for you, does the SaveChanges automatically ignore this on saving or do you need to override the method to handle this ?

    I believe it will automatically ignore readonly properties. You can also apply a [NotMapped] attribute to any property and it will be ignored as part of persistence.

    Hope this helps,

    Scott

  • @Roland,

    >>>>>>> How does it work with other databases ?

    You can use EF Code First with any database that supports an ADO.NET Data Provider. For example, that are providers out there for SQL CE, Oracle and MySQL too.

    Hope this helps,

    Scott

  • @Sergey,

    >>>>>> Nice work! I'm wondering if you guys are planning to add support for sql_variant in the final version - that's what's holding up our migration from LinqToSql to EF.

    Not sure if you saw Jeff's comment above - reporting here in case you missed it:

    The initial Code First release will not include support for sql_variant. This is a feature that is on our list for new data types that we'd add to the full Entity Framework stack (Code First sits on top of this). Unfortunately at this time, there aren't any workarounds is you heavily rely on this type.

    Hope this helps,

    Scott

  • @Jeff,

    >>>>>>> I previously read about support for mapping to existing SPROCs. What is the status? Is it going to make EF4 Code-first before RTM?

    You can use SPROCs to retrieve data and populate entities. These entities can then optionally be change-tracked, so that when you call SaveChanges() they are persisted back in the database.

    What won't be supported in V1 is the ability to override the persistence to use SPROCs. Only the querying of the data can be used via them. I believe the data team is looking at enabling persistence too in the next release.

    Hope this helps,

    Scott

  • @Paul,

    >>>>>>> How do I update my Package Manager Console??? I sill have to use Add-Package and I am not seeing all the packages????

    If you already have NuGet installed, you can go to the Visual Studio "Extensions Manager" and it will show a list of all extensions. Click "update" on NuGet and it will make sure the latest version is installed.

    Hope this helps,

    Scott

  • @willc,

    >>>>>>> I like the idea of data annotations on class properties over using fluent configuration. The trouble is that if you have too many rules it can obscure the structure and function of the class. Would it be possible to give the Visual Studio UI the ability to toggle attribute visibility on and off leaving some sort of placeholder?

    I don't know of any automatic way to do this at the moment. You can, though, use the fluent configuration API to provide your mapping rules and keep them off of your model structure.

    >>>>>>>> Also, does this CTP contain T4 template generation? I had heard that was in the works.

    Yes - CTP5 includes some new T4 template generators that work with the existing EF Designer within VS 2010. It allows the designer to persist the entity shape using EF Code First (and also makes them really easy to tweak).

    Hope this helps,

    Scott

  • @Michael Teper,

    >>>>>>> I haven't played with EF, so this may be a naive question, but why is there a CategoryID on the Product? Isn't that redundant? Who is responsible for setting it?

    The CategoryID is there because the Products table within the Northwind database has a foreign key column named "CategoryID".

    With CTP4 it wasn't necessary to have this always exposed within the model class (instead you could hide it and just expose a property like Category). I've noticed with CTP5 that it seems to need to be there - not sure if that is by design or a regression from CTP4.

    Hope this helps,

    Scott

  • @interorion

    >>>>>> When generating the database in a model-first scenario, does CTP5 allow modification of tables, or does it still drop all of the tables before re-adding them?

    The feature you are looking for is one called "migrations" - and is something we are looking to enable soon. Right now the EF schema change approach only supports recreating the table, and not incremental changes that preserve existing data. Soon though!

    Hope this helps,

    Scott

  • @jdn,

    >>>>> Does this conflict with VS2010 Beta 1 and/or .NET Framework 4 Beta 1?

    This will only work with the released versions of VS 2010 and .NET 4 - or with the SP1 bits of them.

    Hope this helps,

    Scott

  • @Dan H,

    >>>>>>> Still cant get Code-First to create a SQL database in a specific directory (specify either full path for WPF app or |DataDirectory|\... for asp.net app_data dir in the connection string).

    Can you send me email (scottgu@microsoft.com) with more details? I can then connect you with folks on the data team to help.

    Thanks,

    Scott

  • @Matt,

    >>>>>> Can I assume you are referring to RTW/RTM or are you referring to the final CTP?

    I was referring to the final release - which will ship before the end of March.

    Hope this helps,

    Scott

  • @lordosh

    >>>>>>> is there a way to use EF Code First POCO model "metadata" to create custom output? What I am after is a capability to get the model description as EF sees it and then use that to generate some files (pasing it to custom T4 template provider) but without worrying about what property holds primary key or any other convenition (implicit or not). Essentialy, I would be able to just query all model entities, primary keys for each entity, associations etc. Thanks

    If you can send me email (scottgu@microsoft.com) I can connect you with the data team to find out for sure.

    Thanks,

    Scott

  • @Madu,

    >>>>>> When do you plan to implement inheritance in the Entity Framework Code-First? (Table-per-type, Table-per-Hierarchy and Table-per-Concrete-Type)

    This is supported today. Here are some posts to check out on how to use it:

    http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx

    http://blogs.microsoft.co.il/blogs/gilf/archive/2010/12/12/ef-feature-ctp5-inheritance-scenarios-with-code-first-fluent-api.aspx

    Hope this helps,

    Scott

  • @Russ,

    >>>>>>> A big problem is serialzing entities because they end up using the proxies instead. It would be handy if our poco classes could control this by adding an attribute like [ScriptIgnore] to prevent lazy loaded child collections going along for the ride. Another problem this would allow us to easily solve is the circular references when trying to serialize. Or, if there was an easy way to convert between proxied objects and simple poco objects for serialization that would be another solution.

    Jeff answered your comment above - wanted to call that out in case you missed his reply above.

    Thanks,

    Scott

  • @Andre,

    >>>>> What's the approach for creating a new Northwind object (i.e. a new dbContext)? I suppose this is a quite expensive process and we should therefore look best practices for it: singletons, on application start up, unit of work? You get the idea ...

    You can just use "new" on the object. EF internally caches the metadata of the schema at the app-domain level, so you only pay the hit to create it once per application.

    Hope this helps,

    Scott

  • @joydeep1985

    Send me email (scottgu@microsoft.com) if you are still having problems and we can have someone help.

    Thanks,

    Scott

  • @Bernie,

    >>>>>> Is there a change tracking api usage or documentation for the new EF4 CTP5?

    Yes - CTP5 now supports a change-tracking API on the client. I haven't used it personally, but I believe it is pretty rich.

    Hope this helps,

    Scott

  • @Matt,

    >>>>>> How does the validaiton relate to the EntLib validation?

    You can integrate EF Code First with EntLib's validation block. The built-in support with EF Code First doesn't use Entlib - but Entlib can definitely be used with EF Code First.

    Hope this helps,

    Scott

  • @rcm01

    Did you see David Fowler's response to your question above?

    Thanks,

    Scott

  • @Martin,

    >>>>>>> I tried using the EnumDataTypeAttribute but that doesn't seem to work. It always gets the value 0. Has anyone else managed to map to enums?

    Unfortunately EF doesn't support mapping to enums yet. That is on the roadmap for the future, but won't be supported in the initial EF Code First release.

    Sorry,

    Scott

  • @Brian,

    >>>>>> As far as I know, my mapping of the Northwind Customers table is just like in your example.

    Can you post your model? Do you have a CustomerID primary key column (I forget the exact schema for Northwind customers)? Alternatively (because I forget their syntax) apply a [Key] attribute on the primary key column. I think the error you are receiving is because it can't infer the PK.

    Hope this helps,

    Scott

  • @Larry,

    >>>>>> Are there any issues with EditorFor templates in the EditorTemplates folder with CTP 5 Code First? Worked fine with MVC 2 but can't get them to render either with datatype or UI Hint.

    I just tried this with MVC 3 RC2 and am not having any problems. Are you sure the template is in the right folder location?

    Thanks,

    Scott

  • @Magnus,

    >>>>>>> Is the Package Manager supposed to add the files to the FIRST project in the solution. Selecting a project and even marking it as startup project seems to have no effect.

    The Package Manager has a drop-down (the right-most one) that allows you to pick which project it applies to (you can also set a project flag as an argument to commands).

    Hope this helps,

    Scott

  • @scott,
    >>The Package Manager has a drop-down (the right-most one) that allows you to pick which project it applies to (you can also set a project flag as an argument to commands).

    Indeed it does. Thank you for pointing that out!

  • I really like the looks of EF Code-First. I am hoping it will solve some issues we are currently having with standard EF. With 200ish tables, we are getting HUGE EDMX files where VS2010 regularly has Out of Memory exceptions around the EDMX file (about 3.3 MB for the EDMX,5.2MB for the Designer.cs)

    The two things holding us back from using EF more is the lack of support for Stored Procedures. We use them in the EDMX for the data change (DBAs insist on it for 'security and performance reasons'). They reluctantly allowed my app to directly read the tables for LINQ support, but will not allow it otherwise.

    I read above that Code-First does not yet support saving changes via SPROCs - any idea when we can start to see those?

    Thanks!

  • Thank you for the "Key" tip!
    I would never think to reference "System.ComponentModel.DataAnnotations" on my own.
    Hope this helps others who may be new to EF.

    Merry Christmas

  • Hi,
    I'm using RIA and the DomainService class but as Code First doesn't produce a edmx file I can't generate the stubs etc.

    Is there any way to do this or are the any plans to provide an edmx based on my model tpyes and the DbContext ?

    Thanks
    Doug

  • Hi scott ,

    Regarding the Problem which i hav posted i hav mailed u from Joydeepbeyondsky86@gmail.com alongwith a sample database and a sample application due to which i was facing d probs in simple linq query... seems like Cattaneo D another member also hav run into this problem while running EF code first CTP5 ...

    if you have some time ..please look after it :)

    thanks & regards

    Joy

  • Hi Scott & Team,

    That is great work. Can we do Complex Type materialization using Code-First or any trick in EF4?

    I am also having following problem
    I create an entity and it worked fine, database + table was created, data is being saved & retrieved properly. I change my POCO class and now it is throwing following exception

    The model backing the 'SecManager' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

    SecManager is my Context class.
    I tried following code but no use
    System.Data.Entity.Database.DropCreateDatabaseIfModelChanges obj = new System.Data.Entity.Database.DropCreateDatabaseIfModelChanges();
    obj.InitializeDatabase(new SecManager());

    Thanks

  • Thanks for this post, Scott, however I'm having issues with getting joins to work:

    Take code like this:

    public static IQueryable GetAll()
    {
    return from c in Context.Companies
    join v in Context.Vehicles on c.CompanyIdNumber equals v.CompanyIdNumber
    join mt in Context.ModemTypes on v.ModemTypeId equals mt.Id
    select c;
    }

    Gives me the error:

    System.NotSupportedException: The specified LINQ expression contains references to queries that are associated with different contexts.

    From the code above it's obvious that I'm using the same context for both tables I'm joining against, is this a bug in CTP5 or am I missing something?

    Thanks!

  • Hi,

    This framework is fantastic. The one thing it is missing is the .log property which a normal DataContext object has.

    Is there any way to track the SQL queries carried out?

    Many thanks

  • Hi

    What about INotifyPropertyChanged, how it can be implemented? did it automatically supported by EF CTP 5 ?

    Thanks

  • Is it possible to do late binding with Code First? It seems whatever properties I mapped always get loaded. Even if I only try to get IQueryable().FirstOrDefault.UserName

    Thanks

  • We still can't create custom property? Like

    public string FullName{get{return Last+", "+First}}

  • What about entity split where it's not one to one split? Like one table has UserInfo, a second table has UserInfoOptional. And let the User entity map across two tables and do a left join.

    Thanks.

  • @Frank

    Thanks for the note about the .Log property. It's something we hear about frequently and hope to get this feature into the next major EF release. The best thing to do for now is to use Intellitrace and watch the SqlCommand’s execution methods...it’s actually a pretty slick experience during development time.

  • @whoever

    Code First and Entity Framework don't yet support late binding / lazy loading for scalar and complex properties...only for associations. We plan to support the ability to split off large properties into separate entities, but that is not optimal for all scenarios. This feature is coming, but won't be part of the first Code First release.

    Also, you can create custom / computed properties. If you have just a getter, the property should be ignored. If it isn't, add the [NotMapped] attribute to the property.

  • Thanks for the update. When you say "don't yet support ... lazy loading for scalar", does that mean if I have a message table, the message body field always get loaded? Is this a Code First limitation or the entire Entity Framework? That sounds really really bad. I'm having a big struggle trying to convince people EF is the better way to go in term of efficiency and productivity improvement. This, if true, would be a real death blow.

  • @bilalshahzad

    ComplexTypes are fully supported by Code First and the Entity Framework so you can include them in your entities and expect that their values get materialized.

    In terms of your initialization issue, it looks like you are using the DbInitializer incorrectly. All you need to do is set the initializer for your context type by calling this line of code during your application start-up:

    DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges());

  • Jeff, thanks for your dedication working on new year eve.

    If repository returns IQueryable, I can control which field get loaded and it does generate the right select in SQL. The problem is any computed field, as simple as MyField{get {return "test";}}, will not work.

    You got "The specified type member 'MyField' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

    I have quite a few business logic that control what value should be returned and I want them stayed in the entity, rather than spread over to repository or service layer.

    Any solution you can think of? I can do a ToList(), but that brings back all the fields in 3-4 related tables. We already have hundreds of entities, plus DTOs, adding more to deal with these special case isn't practical.

    We are bringing in Gartner, Microsoft and third party security consultant, trying to convince DBAs that EF is better than the dreaded 100% stored procedure approach. But I need some convincing evident to back me up. Please HELP!

  • @whoever

    I've got some ideas on alternatives that may work. Can you send me an email: jeffders microsoft com

    We worked on a proptotype of getting lazy loaded properties work as a "layer on top of EF" feature until core Entity Framework has support, and I've also had some success using Lazy and the event model in Entity Framework to do some interesting things with dependency injection that can likewise simulate lazy loaded properties. There might be some trade-offs so it'd be good to talk through these to see how they'd work for you until we get this feature working natively.

  • What if I have situation like this:

    public class Activity
    {
    public int ActivityId { get; set; }
    public int CreatedById { get; set; }
    public int ExecutedById { get; set; }


    public WebUser CreatedBy { get; set; }
    public WebUser ExecutedBy { get; set; }
    }

    public class WebUser
    {
    public int WebUserId { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    }


    How can I map relations at this example. I have tried some solutions, but none is working. Can someone explain to me good solution please?



  • The above connection string definition fails to work with SQL2008 standard edition when you point the data source to Sql2008 standard addition. We will not use SqlExpress, please provide connection string example that works with CTP5. We are standardizing on MVC3.

  • how could i do, when the property name is ABCDs and the table name is ABCD ?

  • I'm trying to solve a problem with the MVC Tutorials against existing data. I ran across your blog... great information by the way, and I'm trying to work through your EF “Code First” with an Existing Database. I am using what appears to be the final release of EF code first... sorry, but I'm fairly new at this.
    I've tried my own database on SQL Server, the Northwind database on SQL Server, both with VB, and then your completed project with the express version and I keep getting the following error on all three at GridView1.DataBind();.

    Any help would be deeply appreciated.

    Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList().

    This whole issue came about from the need to figure out the issue between table mapping and classes in the MVC tutorials.

    I have seen on your blog and in several other places a number of people that seem to be in a similar situation as myself trying to get the mapping correct with a singular tablename such as album and the plural class such as albums.

    The new MVC tutorial specifically sent a new version of the database plural table names so that they could use singular class names and I've read your existing database blog but I'm still encountering odd issues.

    Any light you can shed on this would also be deeply appreciated.

    Thanks again for all the enlightening information

  • @Madison,

    Can you send me email (scottgu@microsoft.com) about the scenario and I can help?

    Thanks,

    Scott

  • Hi

    I've been having some trouble with the CTP5 release. I'm using EF Code First feature, and no matter which is my choice (SQL, SQLCe), whenever I publish my project to my host (medium trust environment), it fails with a Security Exception. Is there anything I can do about it?

    Thanks

  • Hi

    I've been having some trouble with the CTP5 release. I'm using EF Code First feature, and no matter which is my choice (SQL, SQLCe), whenever I publish my project to my host (medium trust environment), it fails with a Security Exception. Is there anything I can do about it?

    Thanks

  • Hi,
    I am trying to breakdown my project in different modules. Each module will have its own service layer classes, and model project (Project containing EF-CodeFirst-POCO classes).
    Can multiple EF-CodeFirst-POCO --> point to single database? Each module will have serviceHost project which will have code to initialize db...is it a possiblity?

  • How do I ignore interface in the hierarchy for persistence

  • ERROR: Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList().

    The code is wrong, replace code
    GridView1.DataSource = products;

    with:

    GridView1.DataSource = products.ToList();

    Tadeu Costa

  • I've tried today to create a pretty simple website with 3 project - 1) MVC3+Razor, 2) Class Library with EF code first, and 3) WebForms website. So I wanted to have site management done in WebForms but the website front would work on MVC. I made everything that's described here but when I tried to bind my data to GridView I got this error:

    Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList().

    I tried to find the workaround but failed. So I gave up for now... :(

Comments have been disabled for this content.