One-to-one relationship EF database first

你离开我真会死。 提交于 2020-04-30 07:22:48

问题


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.

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.

So for example..

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

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

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

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


回答1:


Your UserDetails should be:

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

You can create a UNIQUE INDEX on your foreign key

CREATE UNIQUE NONCLUSTERED INDEX [IX_UserId] ON [dbo].[UserDetails]
(
    [UserId] ASC
) ON [PRIMARY]



回答2:


Try with a model like this:

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; }
}

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

}

Remember encrypt the password field.



来源:https://stackoverflow.com/questions/30452761/one-to-one-relationship-ef-database-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!