Buscar..


Relaciones uno a muchos

UserType pertenece a muchos Usuarios <-> Los usuarios tienen un UserType

Propiedad de navegación unidireccional con requerido

public class UserType
{
    public int UserTypeId {get; set;}
}
public class User
{
    public int UserId {get; set;}
    public int UserTypeId {get; set;}
    public virtual UserType UserType {get; set;}
}

Entity<User>().HasRequired(u => u.UserType).WithMany().HasForeignKey(u => u.UserTypeId);

Propiedad de navegación unidireccional con opcional (la clave externa debe ser de tipo Nullable )

public class UserType
{
    public int UserTypeId {get; set;}
}
public class User
{
    public int UserId {get; set;}
    public int? UserTypeId {get; set;}
    public virtual UserType UserType {get; set;}
}

Entity<User>().HasOptional(u => u.UserType).WithMany().HasForeignKey(u => u.UserTypeId);

Propiedad de navegación bidireccional con (requerido / opcional, cambiar la propiedad de clave externa según sea necesario)

public class UserType
{
    public int UserTypeId {get; set;}
    public virtual ICollection<User> Users {get; set;}
}
public class User
{
    public int UserId {get; set;}
    public int UserTypeId {get; set;}
    public virtual UserType UserType {get; set;}
}

Necesario

Entity<User>().HasRequired(u => u.UserType).WithMany(ut => ut.Users).HasForeignKey(u => u.UserTypeId);

Opcional

Entity<User>().HasOptional(u => u.UserType).WithMany(ut => ut.Users).HasForeignKey(u => u.UserTypeId);


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow