身份框架2不适
我是新来的身份框架上新的自定义实体的变化,也许我在做什么这里是不是最好的方法,但无论哪种方式,这是我的情景:身份框架2不适
旁“角色”因素,我的应用程序的某些区域应该考虑如果给定的用户连接到给定的“公司”。
我创建了一个新的实体“公司”(非常简单,只有Id和Name)和一个关系实体“UserCompany”(与用户和公司的Id)。我试图使它与身份框架上角色和用户之间使用的结构尽可能相似。
在我的ApplicationDbContext中,我添加了DbSets和一些逻辑,例如向用户添加公司列表。
我面临的问题是“SaveChanges”不会将更改应用到数据库。 *编辑:不引发错误,SaveChanges()的结果为“1”。
这里是我的ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Company> Companies { get; set; }
public DbSet<UserCompany> UserCompanies { get; set; }
//constructors, etc...
public void AddToCompanies(string _userId, params string[] _companyIds)
{
foreach (var companyId in _companyIds)
{
UserCompanies.Add(new UserCompany()
{
UserId = _userId,
DataAreaId = companyId
});
}
int result = this.SaveChanges();
}
}
一个示例代码这里是我如何映射这个“UserCompany”实体
public class UserCompany
{
[Key, Column(Order = 1), ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
[Key, Column(Order = 2), ForeignKey("Company")]
public string DataAreaId { get; set; }
public virtual Company Company { get; set; }
}
在我UserAdminController类我创建了一个私人ApplicationDbContext对象负责用于调用这个逻辑。我怀疑在处理两个不同的上下文来保存这些数据(一个在ApplicationUserManager对象和这个新对象中)的时候存在一些问题,但我不确定这是否真的是问题,或者如果我是在这里丢失别的东西。
任何帮助,将不胜感激!
是在UserCompany
模型应该是这样
public class UserCompany
{
[Key, Column(Order = 1)]
public string UserId { get; set; }
[ForeignKey("UserId ")]
public virtual ApplicationUser ApplicationUser { get; set; }
[Key, Column(Order = 2)]
public string DataAreaId { get; set; }
[ForeignKey("DataAreaId")]
public virtual Company Company { get; set; }
}
,并检查您使用TransactionScope
,而不是提交。 希望它有帮助!
谢谢,实体的变化做到了! –
没问题,快乐编码:) –
你确定这些条目没有被保存到数据库吗?你是否做过手动检查? – JuanR
嗨胡安,我通过SSMS检查,数据不存在 –