我正在尝试使用SimpleMemberships和Entities在我的ContextInitializer类中播种实体框架数据库。我的实体有一个Users键的外键,如下所示,所以我首先填充了我的用户,然后是我的Entites(事件),如下面的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
。所以我怀疑是
提前感谢您的帮助,
我的实体是:
用户:
[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 */
}
答案 0 :(得分:0)
忽略这个问题,问题是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; }
}