Wednesday, 3 October 2012

Tips and Hints: Entity Framework bits and pieces

This is a mix of all sorts of tiny bits I find while using Entity Framework. 

* Singularise tables' names.

Tables generated by EF will be named as plural automatically, in order to switch it to use singleton, the plural convention needs removing from model builder.
public class MyEntity : DbContext, IDisposable
{
public DbSet<Product> Product {get;set;}
public DbSet<Category> Category {get;set;}

public MyEntity(string nameOrConnectionString)
: base(nameOrConnectionString)
{ }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
}
}

* Create a One-To-Many relationship table using Code First, and access it via LINQ.

The following setups are used to configure a one-to-many relationship:
public class Product
{
 public int ProductID { get; set; }

 public int CategoryID { get; set; }
 public Category Category { get; set; }
}

public class Category
{
 public int CategoryID { get; set; }
}

public class MyEntity : DbContext, IDisposable
{
 public DbSet<Product> Product { get; set; }
 public DbSet<Category> Category { get; set; }

 public MyEntity(string nameOrConnectionString)
 : base(nameOrConnectionString)
 { }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
 modelBuilder.Entity<Product>().HasOptional(p => p.Category).WithMany().HasForeignKey(m => m.CategoryID);
        }
}

* Create a Many-To-Many relationship table using Code First, and access it via LINQ.

The following setups are required to configure two tables with many to many relationship: 
public class Product
{
public int ProductID {get;set;}
public ICollection<Category> Category {get;set;}
}

public class Category
{
public int CategoryID {get;set;}
public ICollection<Product> Product {get;set;}
}

public class MyEntity : DbContext, IDisposable
{
public DbSet<Product> Product {get;set;}
public DbSet<Category> Category {get;set;}

public MyEntity(string nameOrConnectionString)
: base(nameOrConnectionString)
{ }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasMany(p => p.Category)
  .WithMany(p => p.Product)
.Map(
m =>
{
m.MapLeftKey("ProductID");
m.MapRightKey("CategoryID");
m.ToTable("ProductCategory");
});
}
}
Three tables, namely "Product", "Category" and "ProductCategory", are created as the result of previous code. Among which, "ProductCategory" is the relationship table containing primary key from "Product" and "Category" tables as its union unique key.

Use the following code to query for the joined result.
var productCategory = this.myEntity.Product
                .Include("Category")
                .Where(p => p.ProductID == productID)
                .ToString();

No comments:

Post a Comment