简体   繁体   English

实体框架:一对一/一对一,C#代码优先

[英]Entity Framework: One to zero/one with C# Code First

Sorry in advance if this has been answered somewhere, but I searched around and could not find the answer. 抱歉,如果在某个地方已经回答了这个问题,但是我四处搜寻,找不到答案。

I am trying to link up UserProfile and Reviewer tables. 我正在尝试链接UserProfile和Reviewer表。 Reviewer is a type of users in the application, so the relationship between the two tables is one (UserProfile) to zero/one (Reviewer). Reviewer是应用程序中的一种用户,因此两个表之间的关系是(UserProfile)为1到零/ 1(Reviewer)。

The UserProfile model is: UserProfile模型是:

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

    public virtual Reviewer Reviewer { get; set; }
} 

Reviewer Class: 评论者类别:

public class Reviewer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    [ForeignKey("UserProfile")]
    public int ReviewerID { get; set; }

    public string Email { get; set; }
    // other properties of Reviewer...

    public virtual UserProfile UserProfile { get; set; }

}

In other words I am trying to set the foreign key UserId as the key of the table Reviewer, with the name as ReviewerID. 换句话说,我试图将外键UserId设置为表Reviewer的键,名称为ReviewerID。

I specify the fluent API as the following: 我将流利的API指定如下:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // other fluent API...

        modelBuilder.Entity<UserProfile>()
                .HasOptional(x => x.Reviewer).WithRequired(x => x.UserProfile);

    }

However, the database generated by Code First is not quite what I wanted. 但是,Code First生成的数据库并不是我想要的。

Suppose I have the following entry in the UserProfile table: UserId = 4, UserName = lostman1 假设我在UserProfile表中具有以下条目:UserId = 4,UserName = lostman1

and I try to manually insert a new record to the Reviewer table: ReviewerID = 4, Email = d@d.com 并且我尝试将新记录手动插入到Reviewer表中:ReviewerID = 4,电子邮件= d@d.com

It turns out that I cannot update the ReviewerID field in the database cause it is an auto-incremented field. 原来,我无法更新数据库中的ReviewerID字段,因为它是一个自动递增的字段。 Moreover, I get the following error: 此外,我得到以下错误:

The data in row 4 was not committed. 第4行中的数据未提交。
Error Source: SQL Server Compact ADO.NET Data Provider. 错误源:SQL Server Compact ADO.NET数据提供程序。
Error Message: A foreign key value cannot be inserted because a corresponding primary key > value does not exist. 错误消息:无法插入外键值,因为相应的主键>值不存在。 [Foreign key constraint name = FK_dbo.Reviewer_dbo.UserProfile_ReviewerID] [外键约束名称= FK_dbo.Reviewer_dbo.UserProfile_ReviewerID]

Whats wrong with my code first setup? 我的代码首次设置有什么问题? Many thanks! 非常感谢!

Seems to me that you need to have a UserID FK relationship between Reviewer and User. 在我看来,您需要在Reviewer和User之间具有UserID FK关系。 In such a design, not all users would have to be reviewers, but all reviewers would have to be a user. 在这种设计中,并非所有用户都必须是审阅者,而是所有审阅者都必须是用户。

I also am starting to think that maybe you are over-complicating things by no utilizing a concept of roles within your system. 我还开始认为,也许您是在不利用系统中角色的概念来使事情变得过于复杂。 Generally, a user vs reviewer would be specified depending upon the roles that a user has. 通常,将根据用户的角色来指定用户与审阅者。 In this manner, all users would be the same and hold the same data in the tables, the only difference would be that the users have different roles. 以这种方式,所有用户将是相同的,并且在表中保存相同的数据,唯一的区别是用户具有不同的角色。

Authorization and authentication also become simplified when using Roles vs doing complicated table joining or nullable FK relationships. 当使用“角色”与进行复杂的表连接或可为空的FK关系时,授权和身份验证也将得到简化。

Not sure if your problem is solved,if not, you can try something like this 不知道您的问题是否解决,如果不能解决,您可以尝试这样

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasOptional(x => x.Reviewer).WithRequired(x => x.User).Map(x => x.MapKey("UserId"));
        base.OnModelCreating(modelBuilder);
    }

And here are my model declaration 这是我的模型声明

public class User
{
    [Key]
    public int UserId { get; set; }
    public string UserName { get; set; }

    public virtual Reviewer Reviewer { get; set; }
}
public class Reviewer
{
    [Key]
    public int ReviewerId { get; set; }

    public virtual User User { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM