Boy*_*smo 4 asp.net-mvc entity-framework asp.net-identity
基本上,我希望有一个可以创建自己故事的用户。
我有这些课程:
public class ApplicationUser : IdentityUser
{
public string DisplayedName { get; set; }
}
public class Story
{
public int Id { get; set; }
public string Content { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
它们在不同的上下文中进行管理,迁移也是如此。像这样的东西。
public class MyDbContext : DbContext
{
public DbSet<Story> Stories { get; set; }
}
public class IdentityContext : IdentityDbContext<ApplicationUser>
{
}
Run Code Online (Sandbox Code Playgroud)
当我尝试添加迁移然后单独更新它们时,它工作正常,但是当我尝试在我的应用程序用户中添加故事集合时。
public class ApplicationUser : IdentityUser
{
public string DisplayedName { get; set; }
public virtual ICollection<Story> Stories { get; set; }
}
public class Story
{
public int Id { get; set; }
public string Content { get; set; }
public string WrittenById { get; set; }
public virtual ApplicationUser WrittenBy { get; set; }
}
public class StoryMap : EntityTypeConfiguration<Story>
{
public StoryMap()
{
HasOptional(s => s.WrittenBy)
.WithMany(s => s.Stories)
.HasForeignKey(s => s.WrittenById)
.WillCascadeOnDelete(false);
}
}
Run Code Online (Sandbox Code Playgroud)
Story然后使用它失败的上下文对我的实体进行迁移MyDbContext。
Data.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
Data.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
Run Code Online (Sandbox Code Playgroud)
但是当我尝试另一种方式时,我将使用它进行迁移,IdentityContext它将创建一个新表Story
目前,有效的方法是合并我的上下文。就像是。
public class MyDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Story> Stories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但必须有一种方法来分别管理它们,对吧?还是我做的都是错的?
您无法在另一个上下文中引用一个上下文中的实体,否则该上下文也会尝试管理这些实体,从而导致有关已存在表的错误。您有两个选择:
如果您实际上不需要两个单独的上下文(即,它们都是代码优先,并且您对所有内容都在一个数据库中感到满意),那么最好和最简单的解决方案就是像您所做的那样合并它们。拥有多个上下文没有任何好处,而且正如您所看到的,还有很多坏处。使用多个上下文的唯一充分理由是您正在处理其他现有数据库。
创建一个简单的列来存储相关的 id(不是外键)。您失去了拥有真正外键的优化和延迟加载的能力,但您至少仍然可以通过这种方式将事物关联起来。本质上,您只需使用其他上下文中相关对象的 id 设置此属性即可。然后,当您需要检索该对象时,只需利用该 id 向其他上下文发出查询即可。换句话说,您只需手动获取对象即可。
不幸的是,这是你唯一的选择。
| 归档时间: |
|
| 查看次数: |
1559 次 |
| 最近记录: |