entity-framework - 使用 EF 4.1 代码优先 Fluent-api 为复杂类型创建外键

标签 entity-framework ef-code-first

以下是我的域实体

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] 列(复杂类型)作为外键

最佳答案

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

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

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

关于entity-framework - 使用 EF 4.1 代码优先 Fluent-api 为复杂类型创建外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7875907/

相关文章:

entity-framework - 具有附加参数的同一实体上的 Entity Framework 多对多关系

entity-framework - 迭代 DbSet<TEntity> 与 IQueryable<out T>

entity-framework - 如何使用Include限制相关数据的数量

asp.net - 如果我使用 InRequestScope(),在哪里执行 DBContext.SaveChanges()

entity-framework - EntityFunctions.TruncateTime 和单元测试

c# - 在单个语句中为多个列设置默认值

entity-framework - 聚合根之间的外键

c# - 使用 Entity Framework 4.1 的代码优先 DataService 中未解析实体

sql-server - 我可以使用备份/恢复来移动使用 EF Code First 创建的数据库吗?

c# - Entity Framework - 错误地执行 2 个选择语句而不是连接