RhythmicSkye
RhythmicSkye

Reputation: 33

Entity Framework Code First - Definining two different relationships

Say I have two models - House and 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; }
}

And

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

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

Many users can be associated with one house so it is a one-to-many relationship. However, there is also another relationship which is a one-to-one relationship between the owner of the house and the house. How would you define this with data annotations? Thanks

Upvotes: 1

Views: 54

Answers (1)

travis.js
travis.js

Reputation: 5281

Give this a try... (this is 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; }
}

Upvotes: 1

Related Questions