在Fluent NHibernate中,您可以设置映射的级联设置,例如
public class StoreMap : ClassMap<Store>
{
public StoreMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Staff)
.Inverse()
.Cascade.None();
HasManyToMany(x => x.Products)
.Cascade.All()
.Table("StoreProduct");
}
}
如何在实体框架“Code First”中完成这项工作?
答案 0 :(得分:14)
如果模型中有一对多的关系,EF代码首先会通过默认约定启用级联删除。所以你真的不需要做任何特别的事情,但让我们考虑一个你想要覆盖约定并关闭级联删除的场景。这就是今天早些时候使用 EF CTP5 的Fluent API完成的工作:
public class Customer
{
public int CustomerId { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
public class StackoverflowContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.HasMany(c => c.Orders)
.WithRequired(o => o.Customer)
.HasForeignKey(o => o.CustomerId)
.WillCascadeOnDelete(false);
}
}