从另一个项目中的实体类向ApplicationUser添加外键

时间:2015-07-10 04:45:30

标签: asp.net-mvc entity-framework-6 asp.net-mvc-5.2

我目前有一个设置,其中我的EF6数据库模型位于名为实体的项目中。但是我有另一个名为 Infrastructure 的项目,它定义了一个继承自IdentityIUser(标准MVC身份验证模块)的 ApplicationUser 类。

基础设施项目了解实体,但不是相反。我的网络项目只知道基础设施

我想要做的是将我的实体项目中定义的几个类/表中的一些外键引用添加到 ApplicationUser 。我可以添加一个字段ok,但它只是一个标准字符串字段,没有外键约束。

这是否可以使用Entity框架?我尝试过使用Fluent注释,但无法弄清楚如何操作。

我的迁移和DBContext都在Infrastructure项目中定义。

项目设置是:

Web
|
 Infrastructure
 | 
  Entities

我的网络项目不了解实体项目,因为我在基础设施中有一个中间层,可以为我做实体模型的映射。

1 个答案:

答案 0 :(得分:1)

您可以向实体项目添加冗余的ApplicationUser,DbSet,config等,并在那里设置关系。然后你可以使用这样的代码:

var infrastructureUser= await UserManager.FindByIdAsync(User.Identity.GetUserId());
var entityUser = db.Users.Find(infrastructureUser.UserID);
myEntity.UserProfile = entityUser;
db.MyEntity.Add(myEntity);
await db.SaveChangesAsync();
return RedirectToAction("Index");

您还可以考虑解耦EF,但这需要做很多工作。 https://jinishbhardwaj.wordpress.com/2014/07/16/decoupling-asp-net-identity-2-0-from-entity-framework-in-mvc5-part-1/