Radzen Professional is now 20% off until January 4th 2019! Learn more

Entity Framework Core relationships

I’ve spent last few days working on code generation for cascade delete support in Radzen and found several important facts about Entity Framework Core that might help you in case you work on something similar.

Entity Framework Core will create automatically one-to-many relationships if you have just navigation property and Key attribute: Northwind Database Diagram — Customers -> OrdersNorthwind Database Diagram — Customers -> Orders

public class Customer
{
  [Key]
  public string CustomerID  { get; set; }

  public ICollection<Order> Orders { get; set; }
}

public class Order
{
  [Key]
  public int OrderID { get; set; }

  public string CustomerID  { get; set; }
}

If you have composite primary key you cannot use only the Key attribute to define composite keys:

Northwind Database Diagram — Order DetailsNorthwind Database Diagram — Order Details

public class OrderDetail
{
  [Key]
  public int OrderID { get; set; }

  [Key]
  public int ProductID { get; set; }
}

This can be done via the Fluent API in your DbContext class OnModelCreating override:

public class NorthwindContext : DbContext
{
  public NorthwindContext(DbContextOptions<NorthwindContext> options):base(options) { }

  public NorthwindContext() { }

  protected override void OnModelCreating(ModelBuilder builder)
  {
    builder.Entity<OrderDetail>().HasKey(table => new {
      table.OrderID, table.ProductID
    });
  }

  public DbSet<Customer> Customers { get; set; }

  public DbSet<Order> Orders { get; set; }

  public DbSet<OrderDetail> OrderDetails { get; set; }
}

If you want to delete principal/parent entity you need to include dependent/child entities:

public void DeleteCustomer(string key)
{
  using (var db = new NorthwindContext())
  {
    var customer = this.context.Customers
      .Where(i => i.CustomerID == key)
      .Include(i => i.Orders)
      .SingleOrDefault();

    if (item != null)
    {
      db.Remove(customer);
      db.SaveChanges();
    }
  }
}

More info about EF Core cascade delete can be found here: https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete

Enjoy!

by Vladimir Enchev

Server paging sorting and filtering with OData and MS SQL Server

I’m happy to announce that with the latest version of Radzen you will be able to configure the DataGrid to page, sort and filter your data…
Read more