- 我需要创建 fluentapi 一对一或零对一引用,并在两个实体上都具有导航属性。
EntityTwo 应该包含简单的属性来存储外键 (EntityOneId)
public class EntityOne { public int Id { get; set; } public EntityTwo EntityTwo { get; set; } } public class EntityTwo { public int Id { get; set; } public int EntityOneId { get; set; } public EntityOne EntityOne { get; set; } } public class MyDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //some code trimmed modelBuilder.Entity<EntityOne>() .HasOptional(entity => entity.EntityTwo) .WithRequired(); modelBuilder.Entity<EntityTwo>() .HasRequired(entity => entity.EntityOne) .WithMany() .HasForeignKey(entity => entity.EntityOneId) .WillCascadeOnDelete(false); } }
更复杂的场景:
public class EntityOne
{
public int Id { get; set; }
public EntityTwo EntityTwo { get; set; }
}
public class EntityThree
{
public int Id { get; set; }
public EntityTwo EntityTwo { get; set; }
}
public class EntityTwo
{
public int Id { get; set; }
public int EntityOneId { get; set; }
public EntityOne EntityOne { get; set; }
public int EntityThreeId { get; set; }
public EntityThree EntityThree { get; set; }
}
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//some code trimmed
modelBuilder.Entity<EntityOne>()
.HasOptional(entity => entity.EntityTwo)
.WithRequired();
modelBuilder.Entity<EntityThree>()
.HasOptional(entity => entity.EntityTwo)
.WithRequired();
modelBuilder.Entity<EntityTwo>()
.HasRequired(entity => entity.EntityOne)
.WithMany()
.HasForeignKey(entity => entity.EntityOneId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EntityTwo>()
.HasRequired(entity => entity.EntityThree)
.WithMany()
.HasForeignKey(entity => entity.EntityThreeId)
.WillCascadeOnDelete(false);
}
}