Steve Wash
Steve Wash

Reputation: 986

EF Code First 1:0..1 relationship shared primary key

I have a relationship that I need to model that is 1:0..1. Class A has a required reference to Class B, but Class B can exist without Class A.

My understanding (which could be wrong) is that this EF can only create this relationship in such a way that Class A does not have its own Primary Key but uses the same Primary Key as Class B. Class A is the dependent entity, Class B is the primary.

Is it possible to edit an existing Class A (with a link to a specific Class B) and change it to link to a different Class B? What happens to its primary key? What happens to other entities that reference Class A?

Upvotes: 0

Views: 643

Answers (1)

potehin143
potehin143

Reputation: 531

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();

something like this

Upvotes: 1

Related Questions