0

使用 EF-Code-First 我想设置一个与 ASP.Net 4.0+ OOTB 附带的内置简单成员资格提供程序相关(1-1)的数据库表

AccountModels.cs 中的 UserProfile 类是一个简单的 2 字段类:

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

我的班级与我想分开的其他用户信息具有以下格式:

[Table("UserInfo")]
public class UserInfo
{
    [Key]
    public int ID { get; set; }
    <user info fields here...>
    public virtual UserProfile UserProfile { get; set; }
}

上下文是:

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<UserInfo> UsersInfo { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserInfo>()
                    .HasRequired(u => u.UserProfile)
                    .WithRequiredPrincipal();
    }
}

现在,无需更改任何其他内容,当我运行应用程序时,模型构建良好,但WebSecurity.CreateUserAndAccount(model.UserName, model.Password);运行时出现错误(Acct Controller Line 82)。The INSERT statement conflicted with the FOREIGN KEY constraint "UserInfo_UserProfile".

存储我希望以后能够直接从数据库中引用的用户信息的(假定的)首选方法是什么(即,根据旧的配置文件提供程序,不在 blob 中)

如何使用 EF-CodeFirst 进行设置,而不是通过存储库层运行所有内容?我应该去存储库路线吗?

当我测试该方法时,我无法让 azureSQL 在 UserProfile 表中包含更多列,因此希望将 userInfo 内容排除在 UserProfile 之外。

谢谢

4

1 回答 1

1

 modelBuilder.Entity<UserInfo>()
                    .HasRequired(u => u.UserProfile)
                    .WithRequiredPrincipal();

意味着您的 UserProfile 类又需要 UserInfo。由于 SimpleMembership 将插入 UserProfile 而不是 UserInfo,因此会引发异常。

我认为您不需要考虑这个问题,因为您的关系是可选的 - UserProfile 将在 UserInfo 之前存在,因为 simplemembership 将在您创建 UserInfo 之前创建它。

http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/257f33d2-9870-46ce-9b0b-147935162a0c

于 2012-11-15T06:18:54.797 回答