带有simplemmembership的种子实体框架和带有外键的实体
本文关键字:实体 框架 simplemmembership 种子 带有 | 更新日期: 2023-09-27 18:02:52
我试图在我的ContextInitializer类与SimpleMemberships和实体种子实体框架数据库。我的实体有一个指向Users表的外键,如下所示,所以我先填充了我的用户,然后填充了我的实体(事件),如下面的ContextInitializer类所示。
protected override void Seed(CustomContext context)
{
WebSecurity.InitializeDatabaseConnection("MyContext", "Users", "UserId", "UserName", autoCreateTables: true);
seedUsers(context);
seedEvents(context);
/* snip */
}
private void seedUsers(CustomContext context)
{
var roles = (SimpleRoleProvider) Roles.Provider;
var membership = (SimpleMembershipProvider) Membership.Provider;
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (membership.GetUser("test", false) == null)
{
membership.CreateUserAndAccount("test", "test");
}
if (!roles.GetRolesForUser("test").Contains("Admin"))
{
roles.AddUsersToRoles(new[] {"test"}, new[] {"Admin"});
}
}
private void seedEvents(InviteeContext context)
{
var membership = (SimpleMembershipProvider) Membership.Provider;
events = new List<Event>()
{
new Event() { name = "Test 1", owner_id = membership.GetUserId("test")},
new Event() { name = "Test 2", owner_id = membership.GetUserId("test")}
};
events.ForEach(p => context.Events.Add(p));
context.SaveChanges();
}
}
当我如上所示创建事件时,我最终得到了正确的结果events[0].owner_id == 1
,我可以看到这在数据库中工作,但是当我去保存它时,我最终得到了外键违反。检查上下文中的Users设置(如下所示),我可以看到它是空的context.Users.Count() == 0
。所以我怀疑要么
- 用户添加略有不同
- 我需要在添加用户后刷新我的上下文(不确定如何做到这一点)
- 我需要创建用户作为一个user类,并将其添加到我的上下文
提前感谢您的帮助,
My Entities are:
用户:[Table("User")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
事件:
public class Event
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int owner_id { get; set; }
[ForeignKey("owner_id")]
public virtual User owner { get; set; }
/* Snip */
}
My Context看起来像这样:
public class CustomContext : DbContext
{
public CustomContext()
: base("name=MyContext")
{
}
public DbSet<Event> Events { get; set; }
public DbSet<User> Users { get; set; }
/* Snip */
}
忽略这个问题,问题是WebSecurity中的一个错别字。InitializeDatabaseConnection或User类。
Web Security在数据库"MyContext"中创建了一个名为Users的表,而我的类创建了一个名为User的表
WebSecurity.InitializeDatabaseConnection("MyContext", "Users", "UserId", "UserName", autoCreateTables: true);
[Table("User")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}