【问题标题】:Creating a foreign key for complex type using EF 4.1 code first fluent-api首先使用 EF 4.1 代码为复杂类型创建外键 fluent-api
【发布时间】:2011-10-24 12:52:19
【问题描述】:

以下是我的域实体

public class User
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string EmailAddress { get; set; }

    public RoleType RoleType { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我已将 RoleType 设为 复杂类型(以实现枚举映射)。所以我可以使用类似context.Users.FirstOrDefault(u => u.RoleType.Value == (long)RoleTypes.Admin) RoleTypes.Admin 是到 Role 实体的枚举映射

public class RoleType
{
    public int Value { get; set; }

    // And all the implicit operators to map with enum
}

然后我使用 fluent api 创建了一个映射

public class RoleTypeMapping : ComplexTypeConfiguration<RoleType>
{
    public RoleTypeMapping()
    {
        Property(r => r.Value)
            .HasColumnName("RoleId"); // To make sure that in RoleType property of User EF entity maps to an int column [RoleId] in database (table [Users])
    }
}

使用 fluent-api,我想在 [Users] 表中为 [Users].[RoleId] 引用 [Role].[Id] 创建一个外键关联。请任何人都可以为我提供指导以实现这一目标

我厌倦了添加 Role 类型的属性并通过 fluent-api 创建映射,但 EF 创建了另一列 Role_Id 并将其设为外键。我希望现有的 [RoleId] 列(复杂类型)成为外键

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:

    这是不可能的。如果您想与 Role 表关联,您必须放弃类似枚举的方法并定义 Users 实体,例如:

    public class User
    {
        public int Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string EmailAddress { get; set; }
    
        public Role Role { get; set; }
    }
    

    首先,关系不是枚举,复杂类型不能包含导航属性(以及外键)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 2012-04-09
      相关资源
      最近更新 更多