我有一个数据库,我使用Database-First到Entity Framework生成模型。
下图显示了数据库中的内容:
当我在我的代码中执行以下操作(插入具有关联角色的用户)时:
using (var context = new ApplicationDbContext())
{
var role = new Role {Name = "Admin"};
var user = new User {UserName = username,
PasswordHash = passwordHash,
Roles = new List<Role> { role }};
context.Set<User>().Add(user);
context.SaveChanges(); //Error here
}
它会抛出以下错误:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
并在 InnerException 中得到:
Invalid object name dbo.RoleUsers
这很奇怪,因为我有一个表 UserRoles ,而不是 RoleUsers 。
有谁知道这里的错误来源是什么?
谢谢, 约努茨