user1477920
user1477920

Reputation: 31

Entity Framework 4.3 one to one foreign key relationship

I am hoping some one will provide me with more insight after spending countless hours configuring the data model of an existing database. I have the following database structure

User (Table)
    UserID  (P.K Identity int)
    UserName (nvarchar)

UserSetting (Table)
    UserSettingsID (P.K Identity int)
    UserSettingsUserID (F.K of User.UserID)

In the model, I have a property UserSetting for user entity and User property on the usersetting entity.

In the user setting entity type configuration;

 this.HasRequired(t => t.User)
     .WithMany(t => t.UserSetting)
     .HasForeignKey(d => d.UserSettingsUserID)
     .WillCascadeOnDelete(false);

The above will only work (this is the only solution I have at the moment) if I make the UserSetting as ICollection in the user entity. I have tried setting foreign key attributes and almost anything I can find on the net but no luck. This is my first time coding with entity framework using repository pattern and unit of work.

Upvotes: 3

Views: 1546

Answers (3)

Danny Varod
Danny Varod

Reputation: 18098

You can use this schema for a 1 to 0..1 entity mapping in EF 4.x:

Table Users
    UserID int, PK, Identity
    UserName nvarchar

Table UserSettings
    UserID int, PK, non-Identity, FK to Users
    Settings nvarchar(max) or any other type

Or this schema for a 1 to 1 entity mapping in EF 4.x (split the table into two entities):

Table Users
    UserID int, PK, Identity
    UserName nvarchar
    Settings nvarchar(max) or any other type

Links for table splitting:
Using DB-First
Using Code-First

Upvotes: 2

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102428

Check this guy's blog for a solution:

http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

Basically:

modelBuilder.Entity<User>().
HasRequired(us => us.UserSetting).
WithMany().
HasForeignKey(u => u.UserSettingId);

Pay close attention to how he structured the User class properties and the properties' names. Names must match accordingly.

By the way: decorating the entities with data annotations is way easier than with the Fluent API.

Upvotes: 2

Wahid Bitar
Wahid Bitar

Reputation: 14104

If you're looking for One to One then the UserSetting table should has one primary key and this key should be foreign key to the User table in the same time :

User (Table) UserID (P.K Identity int) UserName (nvarchar) UserSetting (Table) UserSettingsID (P.K Identity int AND F.K of User.UserID)

Upvotes: 0

Related Questions