一对一关系EF数据库优先 [英] One-to-one relationship EF database first

查看:53
本文介绍了一对一关系EF数据库优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先遇到有关实体框架数据库中一对一关系的问题.

I am having issues regarding one to one relationship in entity framework database first.

我有两个表,一个用户表和一个用户详细信息表.

I have two tables, a user table and a user details table.

用户将包括登录信息,用户名,注册日期,并且userDetails将具有联系方式,网站等信息.在我的数据库中,我的user.id引用了userdetails.userId.两者都是主键.

user would consist of login info, username, date registered and the userDetails would have information such as contact information, website, etc. In my database My user.id references userdetails.userId. Both are primary keys.

例如.

User:
Id [Primary Key (incremented)]
Password
Salt
RegisteredDate

UserDetails
UserId [Primary Key (References User.Id)]
Firstname
Contact

我的问题是我可以通过SQL Server添加记录,但是EF引发异常.

My issue is I can add records through SQL Server but EF throws an exception.

如何在EF 6中成功创建一对一关系?

How can I successfully create a one to one relationship in EF 6?

推荐答案

尝试使用这样的模型:

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

    //navigation property
    public UserDetail UserDetail { get; set; }
}

public class UserDetail
{
    [Key,ForeignKey("User")]
    public int UserId { get; set; }
    //...

    //navigation property
    public User User { get; set; }
}

这正在使用数据注释.如果要使用 Fluent Api ,则可以覆盖通过您的上下文使用OnModelCreating 方法:

This is using Data Annotation. If you want to use Fluent Api, you could override the OnModelCreating method on your Context this way:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure UserId as PK for UserDetail
    modelBuilder.Entity<UserDetail>()
        .HasKey(e => e.UserId);

    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<User>()
                .HasOptional(u => u.UserDetail) // Mark UserDetail as optional for User
                .WithRequired(ud=> ud.User); // Create inverse relationship

}

记住加密密码字段.

这篇关于一对一关系EF数据库优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆