2

我有User可能有零或一ProfileProfile从代码的角度来看,如果我可以访问它应该更方便User(因为我会更频繁地访问用户信息而不是其配置文件),但这与 EF Code First 冲突:

class User
{
    public int Id { get; set; }
    [ForeignKey("Id")]
    public virtual Profile Profile { get; set; }
}
class Profile
{
    public int Id { get; set; }
}

User这放在 DbContext 中,将创建表,如果没有Profile在 => bad 之前创建,我无法创建表,因为这User是显而易见的原则。最简单的(对于愚蠢的我)解决方案很明显:

class User
{
    public int Id { get; set; }
}
class Profile
{
    public int Id { get; set; }
    [ForeignKey("Id")]
    public virtual User User { get; set; }
}

这给了我更多预期的数据库行为。

但是......我觉得这个解决方案不是最好的方法。例如,我无法使用延迟加载通过所有配置文件访问所有用户。所以问题是“如何正确设置一对零/一关系(通过 DataAnnotation 和 FluentAPI)?” 换句话说,“如何正确设置“一User对零/一Profile”的关系?

可能我完全想错了...

4

2 回答 2

2

编辑:

在解决方案中添加了删除时的级联。

尝试这个

public class User
{
    public int Id { get; set; }

    public int? UserProfileId { get; set; }
    public virtual UserProfile Profile { get; set; }
}

public class UserProfile
{
    public int Id { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }
}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasOptional(x => x.Profile).WithRequired(x => x.User).WillCascadeOnDelete(true);

        base.OnModelCreating(modelBuilder);
    }
于 2013-01-09T15:10:57.083 回答
1

Thanks to Drauka. His proposal led me to the solution:

class User
{
    public int Id { get; set; }
    [ForeignKey("Id")]
    public virtual Profile Profile { get; set; }
}
class Profile
{
    public int Id { get; set; }
    [Required, ForeignKey("Id")]
    public virtual User User { get; set; }
}

So the trick is done by Required which marks that the entity, where it is defined, is dependent while the other one is principal. And it saves one collumn in both tables (for foreign key id).

Just one problem remained: how to ensure Profile is deleted in cascade when deleting User?

于 2013-01-09T15:47:12.900 回答