Select theme:
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
Enjoy!
Radzen Blazor Components v12.1: AI Chat with Tool Calling, AIPrompt, Smart Paste, and More
Radzen Blazor Components v12.0: Markdown Editor, Resource Scheduling, Browser Export, and More
34 UI Block categories. 200+ blocks. 1,170+ variants.
The Radzen Roadmap: What's Shipped and What's Next
Blazor Charts Deep Dive: Candlestick, Box Plot, Waterfall, and 30+ More Free Chart Types
Radzen Blazor Components v11.0: Spreadsheet, 30+ New Charts, and More
RadzenSpreadsheet: a Free and Open-Source Blazor Spreadsheet
Radzen is free to use. You can also test the premium features for 15 days.
Start FreeSelect theme: