[英]EF CORE multiple properties that map to the same table
我有這個數據模型,我無法讓它工作。
一個User
可以同時關聯到一個Company
和多個。
但是一個Company
有多個Users
下面的圖片示例: 我試圖像這樣在模型構建器上設置關系:
builder
.HasMany(c => c.Users)
.WithOne(u => u.CurrentAssociatedCompany)
.HasForeignKey(u => u.CurrentAssociatedCompanyId)
.IsRequired();
但我在遷移中遇到錯誤
值不能為空。 (參數'鍵')
甚至研究過 InverseProperty 但也沒有運氣。
我的問題是,是否有可能實現這一目標,還是應該嘗試不同的方法?
從User
和Company
之間的關系,您可以設計如下所示的模型:
模型
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public int Age { get; set; }
public int CurrentAssociatedCompanyId { get; set; }
public Company CurrentAssociatedCompany { get; set; }
public ICollection<UserCompany> UserCompanies { get; set; }
}
public class Company
{
public int Id { get; set; }
public string CompanyName { get; set; }
public ICollection<UserCompany> UserCompanies { get; set; }
}
public class UserCompany
{
public int UserId { get; set; }
public User User { get; set; }
public int CompanyId { get; set; }
public Company Company { get; set; }
}
數據庫上下文
public class MVCDbContext : DbContext
{
public MVCDbContext(DbContextOptions<MVCDbContext> options) : base(options)
{ }
public DbSet<User> User { get; set; }
public DbSet<Company> Company { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserCompany>()
.HasKey(uc => new { uc.UserId,uc.CompanyId });
modelBuilder.Entity<UserCompany>()
.HasOne(uc=>uc.Company)
.WithMany(c => c.UserCompanies)
.HasForeignKey(uc=>uc.CompanyId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserCompany>()
.HasOne(uc => uc.User)
.WithMany(u => u.UserCompanies)
.HasForeignKey(uc => uc.UserId)
.OnDelete(DeleteBehavior.Restrict);
}
}
控制器
public IActionResult GetUserData(int? id)
{
var userData = _context.User
.Include(u => u.CurrentAssociatedCompany)
.Include(u => u.UserCompanies)
.ThenInclude(uc => uc.Company)
.Where(u=>u.Id==id)
.Select(u => new
{
UserId = u.Id,
UserName = u.UserName,
Age = u.Age,
CurrentAssociatedCompany = u.CurrentAssociatedCompany.CompanyName,
AssociatedCompanies = u.UserCompanies.Select(uc => new {
Id=uc.Company.Id,
CompanyName=uc.Company.CompanyName
}).ToList()
});
return Json(userData);
}
對於 EF Core 中的多對多關系,可以參考官方文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.