【发布时间】:2013-01-30 16:45:27
【问题描述】:
我已经有一段时间了,我真的无法弄清楚。我正在使用 EF5、Mvc 4、table-per-type 继承。
我有继承自 UserProfile 的租户和房东类。注册用户时选择他们想要的帐户类型,并根据此选择将他们在表单上输入的详细信息(用户名、名字、姓氏、电子邮件、帐户类型、密码)添加到 UserProfile 表中。然后,我希望将该表的 PK 作为外键添加到与他们选择的帐户类型(租户或房东)匹配的表中。
我试图实现上述using this method,但这导致了该问题中描述的问题。
我现在创建了一个 RegisterTenantModel 类,其属性映射到租户,并且我正在将 RegisterTenantModel 类型的对象传递给 AccountController/Register,如下所示...
// ...
if (tenantModel.AccountType == AccountType.Tenant)
{
using (var db = new LetLordContext())
{
var t = db.UserProfile.Create<Tenant>();
WebSecurity.CreateUserAndAccount(tenantModel.UserName, tenantModel.Password,
t = new Tenant
{
AccountType = tenantModel.AccountType,
DateWantToRentFrom = DateTime.Now,
DateWantToRentTo = DateTime.Now,
DesiredPropertyLocation = "",
Email = tenantModel.Email,
FirstName = tenantModel.FirstName,
UserId = WebSecurity.CurrentUserId,
UserName = WebSecurity.CurrentUserName
// More properties that map to Tenant entity
// ...
},
false);
db.SaveChanges();
...但是现在t= new Tenant 中的每个列名都出现错误Invalid column name。
有没有人做过类似的事情?我以正确的方式接近这个吗?非常感谢您的帮助。
编辑
根据 Antonio Simunovic 在下面发布的内容,我想我已经意识到问题所在了。我的WebSecurity.InitializeDatabaseConnection() 是这样的……
WebSecurity.InitializeDatabaseConnection("LetLordContext", "UserProfile",
"UserId", "UserName", autoCreateTables: true);
...所以当我在AccountController/Register 中调用Websecurity.CreatUserAndAccount() 时,它会根据WebSecurity.InitializeDatabaseConnection() 中的参数写入UserProfile 表。查看上面链接的问题,您会看到,根据表单上选择的帐户类型,将通过调用将租户或房东添加到 UserProfile 表中......
var tenant = db.UserProfile.Create<Tenant>();
//...
db.UserProfile.Add(tenant);
db.SaveChanges();
...导致重复的条目被添加到 UserProfile 表中。
我认为解决方案是创建一个新表,并将WebSecurity.InitializeDatabaseConnection() 指向它。
【问题讨论】:
-
我认为你的编辑是正确的。在我所有成员资格的实现中,我已将其配置为使用我的用户表,而不是默认的成员资格/其他特定于成员资格框架的表。我不知道这是最佳实践,但是当不直接使用它时,这是我一直看到的方式。 (也不是 100% 确定这条评论是相关的)。
-
刚刚尝试过,它可以工作,可能不是很漂亮,但每个类型的表继承与成员资格一起工作。感谢您的帮助。
标签: c# asp.net-mvc database entity-framework