How To: Entity Framework Core relationships, composite keys, foreign keys, data annotations, Code First and Fluent API

Vladimir Enchev
Radzenhq
Published in
2 min readFeb 28, 2017

--

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 -> 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 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

Download the latest version of Radzen and register for more updates:
http://www.radzen.com/#download

Enjoy!

--

--

Vladimir Enchev
Radzenhq

Passionate engineer with 25 years in web, desktop and mobile. Led teams & divisions in @Telerik for a decade. Former @NativeScript lead. Co-Founder of @RadzenHQ