【发布时间】:2019-10-14 15:23:26
【问题描述】:
我正在尝试添加一个新用户和一些其他关联实体,包括作为一个交易的声明。我的课程基本上定义如下。请注意,我在 User 类上使用了 int 主键,它是一个标识列(值由数据库在插入时提供)。
public class User : IdentityUser<int>
{
// custom props here
}
public class UserClaim : IdentityUserClaim<int>
{
// i actually haven't added anything to this class, it's mainly here so
// i don't have to keep specifying the user's primary key type
}
public class OtherEntity
{
public int UserId { get; set; }
[ForeignKey(nameof(UserId))]
public User User { get; set; }
// other stuff
}
然后我想将用户等添加到数据库中,如下所示:
User user = new User(){ /* set props */ };
OtherEntity other = new OtherEntity()
{
User = user
};
UserClaim claim = new UserClaim()
{
/* this is where the problem is */
UserId = user.Id,
ClaimType = "my-claim-type",
ClaimValue = "my-claim-value"
};
context.AddRange(user, other, claim);
context.SaveChanges();
我可以轻松地将User 链接到OtherEntity,因为我已经设置了导航属性,所以我可以将User 添加到其中,并且实体框架负责填充UserId 列。我不能用UserClaim 做到这一点,因为它没有导航属性。我可以在添加User 后调用context.SaveChanges(),实体框架将获得由数据库为我创建的User.Id,我可以使用它在UserClaim 上设置UserId,但这意味着两个事务。
我已尝试将导航属性添加到我的UserClaim 定义中,如下所示:
public class UserClaim : IdentityUserClaim<int>
{
[ForeignKey(nameof(UserId))]
public User User { get; set; }
}
但我得到以下运行时错误:
InvalidOperationException:从 'UserClaim.User' 到 'User' 与外键属性 {'UserId' : int} 的关系不能以主键 {'Id' : int} 为目标,因为它不兼容。为此关系配置一个主键或一组兼容的外键属性。
有没有办法在同一个事务中同时创建用户和声明?
【问题讨论】:
标签: asp.net entity-framework asp.net-identity