Entity Framework (code first) From one to many and from one to one (with two entities). How?

I am trying to do this with EF Code First:

database model

There are two tables in the area: users and areas. One User belongs to one required area, and one Area can have zero or one User (as an administrator). Then:

Users * .. 1 Areas and Users 0..1 Areas

Users class:

public class User {
    public int UserId { get; set; }
    public string Name { get; set; }

    [ForeignKey("Area")]
    public int AreaId { get; set; }
    [InverseProperty("Usuarios")]
    public virtual Area Area { get; set; }

    public virtual Area AreaTitular { get; set; }
}

Areas Class:

public class Area {
    public int AreaId { get; set; }
    public string Name { get; set; }

    public List<Usuario> Usuarios { get; set; }

    [ForeignKey("Usuario")]
    public int? UsuarioId { get; set; }
    [InverseProperty("AreaTitular")]
    public virtual Usuario Usuario { get; set; }
}

And the update-database command error:

The main end of the relationship between the types TestEntityFrameworkCodeFirst.Model.Area and TestEntityFrameworkCodeFirst.Model.Usuario cannot be determined. The main end of this association must be explicitly configured using either the free API API or data annotations.

Any help would be greatly appreciated :)

I'm not quite sure that this is normal:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    modelBuilder.Entity<Area>()
        .HasOptional(i => i.Usuario)
        .WithOptionalDependent();
    base.OnModelCreating(modelBuilder);
}

OnModelCreating Context. SQL Server:

Database

+4
1

" ", , . , Entity Framework , . UsuarioId FK, EF , FK PK (, ). , EF , . , , Required. , , AreaTitular, , User AreaTitular , Area, dependend User, escenario, . :

, , . , Data Annotations Fluent Api :

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
        modelBuilder.Entity<User>()
            .HasRequired(a => a.Area)
            .WithMany(c => c.Usuarios)
            .HasForeignKey(a => a.AreaId);

        modelBuilder.Entity<Area>()
            .HasOptional(a => a.Usuario)
            .WithOptionalPrincipal(u => u.AreaTitular);
   }

, " ".

+3

All Articles