实体框架4.3一对一的外键关系

时间:2012-06-24 10:28:08

标签: entity-framework repository-pattern relationship entity-framework-4.3 one-to-one

我希望在花费无数个小时配置现有数据库的数据模型后,有人会为我提供更多见解。我有以下数据库结构

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

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

在模型中,我在useretting实体上有用户实体和User属性的属性UserSetting。

在用户设置实体类型配置中;

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

如果我在用户实体中将UserSetting设置为ICollection,则上述仅适用(这是我目前唯一的解决方案)。我已经尝试设置外键属性和几乎我能在网上找到的任何东西,但没有运气。这是我第一次使用存储库模式和工作单元编写实体框架。

3 个答案:

答案 0 :(得分:2)

检查这家伙的博客是否有解决方案:

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

基本上:

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

密切关注他如何构建User类属性和属性的名称。名称必须相应匹配。

顺便说一句:使用数据注释装饰实体比使用Fluent API更容易。

答案 1 :(得分:2)

您可以将此架构用于EF 4.x中的1到0..1实体映射:

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

或者此模式用于EF 4.x中的1对1实体映射(将表拆分为两个实体):

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

表格拆分的链接:
Using DB-First
Using Code-First

答案 2 :(得分:0)

如果您正在寻找一对一,那么UserSetting表应该有一个主键,并且该键应该同时是User表的外键:

用户(表)UserID(P.K Identity int)用户名(nvarchar) UserSetting(表)UserSettingsID(P.K Identity int和F.K of User.UserID)