EF Code First 1:0..1关系共享主键

时间:2014-01-17 14:19:08

标签: c# entity-framework ef-code-first

我有一个我需要建模的关系是1:0..1。 A类必须引用B类,但B类可以不存在A类。

我的理解(可能是错误的)是这个EF只能创建这种关系,使得A类没有自己的主键,但使用与B类相同的主键.A类是依赖实体,B类是主要的。

是否可以编辑现有的A类(带有指向特定B类的链接)并将其更改为链接到不同的B类?它的主键会发生什么变化?引用A类的其他实体会发生什么?

1 个答案:

答案 0 :(得分:1)

public partial class PrimaryEntity
{
    public PrimaryEntity()
    {
        ID = Guid.NewGuid();
    }
    [Key]
    public Guid ID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

public partial class DependentEntity
{
    public DependentEntity()
    {
        ID = Guid.NewGuid();
    }
    [Key]
    public Guid ID { get; set; }
    public string Name { get; set; }

    public Guid CurrentPrimaryEntityId { get; set; }
    public virtual PrimaryEntity CurrentPrimaryEntity { get; set; } 
}
    // override this in DataContext
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<DependentEntity>().HasRequired(a => a.CurrentPrimaryEntity).WithMany().HasForeignKey(a => a.CurrentPrimaryEntityId);
        base.OnModelCreating(modelBuilder);
    }

 protected override void Seed(MyDataComtext db)
    {
        // here is a restriction that FK must be unique
        db.Database.ExecuteSqlCommand("ALTER TABLE dbo.[DependentEntity] ADD CONSTRAINT uc_Dependent UNIQUE(CurrentPrimaryEntityId)");

    }

var primary = new PrimaryEntity();
 db.PrimaryEntity.Add(PrimaryEntity);
var dependent = new DependentEntity();
dependent.CurrentPrimaryEntity = primary;  
  db.DependentEntity.Add(dependent);
  db.SaveChanges();

类似这样的事情

相关问题