【发布时间】:2013-06-21 14:37:51
【问题描述】:
我有一个 MVC4 项目,它使用实体框架 5(代码优先)和代码优先迁移。该网站使用SimpleMembership。我正在尝试播种 users 表,但遇到与导航属性设置相关的错误。
我有一个 Account 和 User 模型。 SimpleMembership 使用 User 模型作为我的自定义 users 表。这种关系是一对多的,每个User 有一个Account,但每个Account 有很多Users。我试图在种子时间将User 设置为Account 关系,但我无法做到。
模型(无关属性省略):
public class User
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Description { get; set; }
public int AccountId { get; set; }
public virtual Account Account { get; set; }
}
public class Account
{
[Key]
public int AccountId { get; set; }
public string Name { get; set; }
// Account has many users but only one "admin" user. ID manually set.
// Nullable because of chicken / egg problem (user requires account, account requires user)
public int? AdminUser { get; set; }
public virtual ICollection<User> Users { get; set; }
}
种子方法:
protected override void Seed(MyProject.Data.MyContext context)
{
WebSecurity.InitializeDatabaseConnection("MyContext", "Users", "UserId", "UserName", autoCreateTables: true);
Account adminAccount = new Account()
{
Name = "Dev",
Description = "Dev account"
};
context.Accounts.AddOrUpdate(adminAccount);
if (!WebSecurity.UserExists("dev@dev.com"))
{
WebSecurity.CreateUserAndAccount("dev@dev.com", "password", new User()
{
Email = "dev@dev.com",
FirstName = "Dev",
LastName = "Guy"
// Problematic properties - see below
// Account = adminAccount,
// AccountId = adminAccount.AccountId
});
}
}
当我打电话给WebSecurity.CreateUserAndAccount 时,我似乎遇到了介绍问题:
-
如果我尝试包含导航属性
Account = adminAccount,则会收到错误消息:"No mapping exists from object type MyProject.Models.Account to a known managed provider native type." -
如果我尝试仅包含 FK 引用
AccountId = adminAccount.AccountId我会收到错误:"Invalid column name 'Account'" -
如果我不包括
Account或AccountId,我也会得到"Invalid column name 'Account'"
我应该指出,我只在我的类中使用导航属性。当我添加外键属性时,一切都爆炸了(存在与 FK 相关的错误,但我无法很好地重现它们以将它们发布在这里,它们可能与我的数据库相关,需要重新创建。我看到了上面- 使用新的无表数据库时出错。
另外,我使用 SQL Azure 作为我的 SQL 数据库。
这似乎是SimpleMembership 的常见用例;我不知道它给我带来了这么多麻烦。
【问题讨论】:
标签: asp.net-mvc-4 entity-framework-5 azure-sql-database entity-framework-migrations seeding