Reputation: 33
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
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