EF Including Other Entities (Generic Repository pattern)

Use just the Include extension on IQueryable. It is available in EF 4.1 assembly. If you don’t want to reference that assembly in your upper layers create wrapper extension method in your data access assembly. Here you have example: public static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query, params Expression<Func<T, object>>[] includes) where T : class { if … Read more

Default value for Required fields in Entity Framework migrations?

In addition to the answer from @webdeveloper and @Pushpendra, you need to manually add updates to your migration to update existing rows. For example: public override void Up() { Sql(“UPDATE [dbo].[Movies] SET Title=”No Title” WHERE Title IS NULL”); AlterColumn(“dbo.Movies”, “Title”, c => c.String(nullable: false,defaultValue:”MyTitle”)); } This is because AlterColumn produces DDL to set the default … Read more

Multiple DB Contexts in the Same DB and Application in EF 6 and Code First Migrations

Entity Framework 6 added support for multiple DbContexts by adding the -ContextTypeName and -MigrationsDirectory flags. I just ran the commands in my Package Manager Console and pasted the output below… If you have 2 DbContexts in your project and you run enable-migrations, you’ll get an error (as you probably already know): PM> enable-migrations More than … Read more

Calculated column in EF Code First

You can create computed columns in your database tables. In the EF model you just annotate the corresponding properties with the DatabaseGenerated attribute: [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public double Summ { get; private set; } Or with fluent mapping: modelBuilder.Entity<Income>().Property(t => t.Summ) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed) As suggested by Matija Grcic and in a comment, it’s a good idea to make … Read more

Composite Key with EF 4.1 Code First

You can mark both ActivityID and ActivityName properties with Key annotation or you can use fluent API as described by @taylonr. Edit: This should work – composite key defined with annotations requires explicit column order: public class ActivityType { [Key, Column(Order = 0)] public int ActivityID { get; set; } [Key, Column(Order = 1)] [Required(ErrorMessage … Read more

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there’s a relationship in there: public class Order { public int ID { get; set; } // Some other properties // Foreign key to customer public virtual Customer Customer … Read more