实体框架代码优先 - 定义两种不同的关系

时间:2017-02-18 01:58:58

标签: c# entity-framework

说我有两个型号 - House和User

class User
{
    [Key, Required]
    public Guid UserId { get; set; }
    public virtual House ILiveHere { get; set; }

    [Required]
    public string Firstname { get; set; }
    [Required]
    public string Lastname { get; set; }
}

class House
{
    [Key, Required]
    public Guid HouseId { get; set; }

    [Required]
    public virtual User HouseOwner { get; set; }
}

许多用户可以与一个房子相关联,因此它是一对多的关系。然而,还有另一种关系,即房屋所有者和房屋之间的一对一关系。您如何使用数据注释定义它?感谢

1 个答案:

答案 0 :(得分:1)

尝试一下......(这是EF Core)

public class MyDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<House> Houses { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"...");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<House>().HasMany(x => x.Residents).WithOne(x => x.House);
    }
}

public class User
{
    [Key, Required]
    public Guid UserId { get; set; }
    public virtual House House { get; set; }

    [Required]
    public string Firstname { get; set; }
    [Required]
    public string Lastname { get; set; }
}

public class House
{
    [Key, Required]
    public Guid HouseId { get; set; }

    public List<User> Residents { get; set; }

    [Required]
    public virtual User HouseOwner { get; set; }
}