【发布时间】:2021-12-23 22:32:18
【问题描述】:
我有一个简单的多对一关系:
public class Company
{
public IEnumerable<User> Users { get; set; }
public int Id { get; set; }
}
public class User
{
public int CompanyId { get; set; }
[Required]
public Company Company { get; set; }
public int Id { get; set; }
}
我还尝试将我的用户定义为以下(没有成功):
public class User
{
[Required]
[ForeignKey("Company")]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
public int Id { get; set; }
}
我有以下方法将新用户添加到公司:
public async Task<bool> Add(User user)
{
try
{
await this.context.Set<User>().AddAsync(user);
await this.context.SaveChangesAsync();
return true;
}
catch (Exception)
{
return false;
}
}
我这样称呼这个方法:
var company = await this.companyService.Get(1); // this works
if (company == null)
{
return;
}
await this.userService.Add(
new User
{
CompanyId = company.Id,
Company = company, // I also tried to remove this line - no effect
});
我的 DbContext 如下所示:
public class AppContext : IdentityDbContext
{
public AppContext(DbContextOptions<AppContext> options)
: base(options)
{
}
public DbSet<Company> Company { get; set; }
public DbSet<User> User { get; set; }
}
既然我已经解释了场景,那么问题就来了。当我将用户添加到公司时,所有条目都将被删除。 “删除”是什么意思?整个表“用户”是空的,没有任何条目。在我添加用户并检查 company 之前,我可以看到所有用户。如果我在插入后再次获取公司,则属性 Users 返回一个空列表(非空)。这也会影响值的删除和更新。我已经在这个问题上坐了 3 天,完全不知道我做错了什么。
【问题讨论】:
标签: asp.net database entity-framework