gpt4 book ai didi

c# - 映射到同一个表的 EF CORE 多个属性

转载 作者:行者123 更新时间:2023-12-04 04:16:10 29 4
gpt4 key购买 nike

我有这个数据模型,但我无法让它工作。
一个用户可以同时关联到一个公司多个。
但是 Company 有多个 Users
下图示例: enter image description here我试过像这样在 modelBuilder 上设置关系:

 builder
.HasMany(c => c.Users)
.WithOne(u => u.CurrentAssociatedCompany)
.HasForeignKey(u => u.CurrentAssociatedCompanyId)
.IsRequired();

但是我在迁移中遇到错误

Value cannot be null. (Parameter 'key')

甚至研究了 InverseProperty,但也没有运气。
我的问题是,是否有可能实现这一点,还是我应该尝试不同的方法?

最佳答案

根据 UserCompany 之间的关系,您可以设计如下所示的模型:

模型

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; }
}

DbContext

 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);
}
}

Controller

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);
}

结果 enter image description here

EF Core 中的多对多关系,可以引用the official doc.

关于c# - 映射到同一个表的 EF CORE 多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60668890/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com