I'm trying to do this with EF Code First:
There area two tables: Users and Areas. One User belongs to one required area and one Area can have zero or one User (as administrator). Then:
Users *..1 Areas and Users 0..1 Areas
The Users class:
public class User {
public int UserId { get; set; }
public string Name { get; set; }
[ForeignKey("Area")]
public int AreaId { get; set; }
[InverseProperty("Users")]
public virtual Area Area { get; set; }
public virtual Area AreaTitular { get; set; }
}
The Areas class:
public class Area {
public int AreaId { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
[ForeignKey("User")]
public int? UserId { get; set; }
[InverseProperty("AreaTitular")]
public virtual User User{ get; set; }
}
And the error on update-database command:
Unable to determine the principal end of an association between the types 'TestEntityFrameworkCodeFirst.Model.Area' and 'TestEntityFrameworkCodeFirst.Model.User'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Any help will be very appreciated :)
I'm not completely sure if this is ok:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Area>()
.HasOptional(i => i.User)
.WithOptionalDependent();
base.OnModelCreating(modelBuilder);
}
Just added this on the OnModelCreating on the Context class. And this is how it looks in SQL Server: