我有这些课程:
public class A
{
public A()
{
nameA = string.Empty;
ListB = new List<B>();
}
public string nameA { get; set; }
public List<B> ListB { get; set; }
}
public class B
{
public C cObject { get; set; }
public string nameB { get; set; }
}
public class C
{
public string nameC { get; set; }
}
我使用Microsoft.EntityFrameworkCore
为这些模型使用数据库,我能够生成数据库和正确的表格,但我错过了两件事:
以下是我的上下文文件中的代码:
public class Context : DbContext
{
#region Tables
public DbSet<A> As{ get; set; }
public DbSet<B> Bs { get; set; }
public DbSet<C> Cs { get; set; }
#endregion
public Context(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//primary key's
modelBuilder.Entity<A>().HasKey(x => x.nameA);
modelBuilder.Entity<B>().HasKey(x => x.nameB);
modelBuilder.Entity<C>().HasKey(x => x.nameC);
//foreign key's
modelBuilder.Entity<A>().HasMany<B>(app => app.ListB);
modelBuilder.Entity<B>().HasOne<C>(app => app.cObject);
base.OnModelCreating(modelBuilder);
}
}
答案 0 :(得分:0)
您可以根据需要使用以下代码。您必须使用A
表的PK作为B
和C
表PK中的外键作为B
上的外键。如果您需要DeleteBehavior.Cascade
,则必须使用Required
。或者您可以使用Fluent API执行此操作。
public class A
{
public A()
{
nameA = string.Empty;
ListB = new List<B>();
}
public string nameA { get; set; }
public List<B> B{ get; set; }
}
public class B
{
public int CForeignKey { get; set; }
[ForeignKey("CForeignKey")]
public C C { get; set; }
public string nameB { get; set; }
[Required]
public int AForeignKey { get; set; }
[ForeignKey("AForeignKey")]
public A A {get; set;}
}
public class C
{
public string nameC { get; set; }
}
Fluent API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<B>()
.HasOne(p => p.A)
.WithMany(b => b.B)
.OnDelete(DeleteBehavior.Cascade);
}