我正在尝试使用 SimpleMemberships 和实体在我的 ContextInitializer 类中播种实体框架数据库。我的实体有一个用户表的外键,如下所示,所以我首先填充了我的用户,然后是我的实体(事件),如下面的 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
,并且我可以在数据库中看到它正在运行,但是当我去保存它时,我最终会遇到外键违规。检查上下文中设置的用户(如下所示),我可以看到它是空的context.Users.Count() == 0
。所以我怀疑要么
- 添加的用户略有不同
- 添加用户后我需要刷新我的上下文(不知道该怎么做)
- 我还需要将用户创建为 User 类并将其添加到我的上下文中
提前感谢您的帮助,
我的实体是:
用户:
[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 */
}
我的上下文如下所示:
public class CustomContext : DbContext
{
public CustomContext()
: base("name=MyContext")
{
}
public DbSet<Event> Events { get; set; }
public DbSet<User> Users { get; set; }
/* Snip */
}