问题
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