提前致谢!我在获取循环引用时遇到问题,其中EntityA具有EntityB的可空外键,而EntityB具有对EntityA的不可空(强制)引用。我已经创建了一个示例来演示,但我无法通过外键让EntityA引用EntityB:
public class EntityA
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public EntityB MasterEntityB { get; set; }
public int? MasterEntityBId { get; set; }
}
public class EntityB
{
public string Name { get; set; }
public int Id { get; set; }
public EntityA EntityA { get; set; }
public int AssociationTypeId { get; set; }
}
public class DataContext : DbContext
{
public DataContext()
: base("CyclicTest")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<EntityB>()
.HasRequired(t => t.EntityA)
.WithOptional(a => a.MasterEntityB)
.WillCascadeOnDelete(false);
}
public DbSet<EntityB> Tenants { get; set; }
public DbSet<EntityA> AssociationTypes { get; set; }
}
以下是我的移民:
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.EntityAs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Description = c.String(),
MasterEntityBId = c.Int(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.EntityBs",
c => new
{
Id = c.Int(nullable: false),
Name = c.String(),
AssociationTypeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.EntityAs", t => t.Id)
.Index(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.EntityBs", "Id", "dbo.EntityAs");
DropIndex("dbo.EntityBs", new[] { "Id" });
DropTable("dbo.EntityBs");
DropTable("dbo.EntityAs");
}
}
我可以手动更改迁移,因此它是一个外键,如下所示:
CreateTable(
"dbo.EntityAs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Description = c.String(),
MasterEntityBId = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.EntityBs", t => t.MasterEntityBId);
CreateTable(
"dbo.EntityBs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
EntityAId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.EntityAs", t => t.EntityAId)
.Index(t => t.Id);
但是当我插入EntityB时,我发现我收到了一个错误:&#34;无法在表格中插入明确的标识值&#39; EntityB&#39;当IDENTITY_INSERT设置为OFF时。&#34;
再次感谢帮助! -max
答案 0 :(得分:0)
好的,我发现了问题。我没有通过虚拟馆藏从A到B的一对多参考。这足以解决问题。此外,我已决定使用子类作为主参考,因此我不需要从B返回A的第二个引用作为主实例。对于所有其他实例,这将为null,并且可能导致重复打破MasterB和A之间的0或1对1预期关系。即:
public class EntityA
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
**public ICollection<EntityB> EntityBs { get; set; }**
public MasterEntityB MasterEntityB { get; set; }
public int? MasterEntityBId { get; set; }
}
public class MasterEntityB : EntityB
{
}
public class EntityB
{
public string Name { get; set; }
public int Id { get; set; }
public EntityA EntityA { get; set; }
public int EntityAId { get; set; }
}