ef-code-first - EF-Code First 复杂类型的导航属性外键

标签 ef-code-first entity-framework-6

我有复杂的审计字段类型

我的复杂类型:

[ComplexType]
public class AuditData  {
    [Column("CreatorUserId")]
    public int? CreatorUserId { get; set; }
    public DateTime? CreationTime { get; set; }
    [Column("ModifierUserId")]
    public int? ModifierUserId { get; set; }
    public DateTime? ModificationTime { get; set; }
}

我的基本实体(所有其他继承者)具有 AuditData 属性:
public abstract class Entity : IEntity, IAuditedEntity, INotifiedDbContextBeforeSave
{

    // Summary:
    //     Unique identifier for this entity.
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public int Old_Id { get; set; }
    public string Old_TableName { get; set; }        
    [Timestamp]
    public byte[] RowVersion { get; set; }        
    public AuditData AuditData { get; set; }
    // can this 2 lines below work as navigation property with foreign key in complex type
    public virtual User CreatorUser { get; set; }
    public virtual User ModifierUser { get; set; }

    //... other fields
}

我有 2 个导航属性 CreatorUser 和 ModifierUser。
我知道你不能在 ComplexType 中拥有导航属性,但是我在实体上的导航属性可以与 complexType 中的外键映射

就像是:
    [ForeignKey("CreatorUserId")] // --> should point to AuditData.CreatorUserId
    public virtual User CreatorUser { get; set; }

因为 CreatorUserId 将是每个实体的属性,但 EF 不知道它。
Mybe 在 fluent API 中有解决方案吗?

最佳答案

official documentation说:

Complex types are non-scalar properties of entity types that enable scalar properties to be organized within entities. Like entities, complex types consist of scalar properties or other complex type properties. Because complex types do not have keys, complex type objects cannot be managed by the Entity Framework apart from the parent object.



由此可见,复杂类型不能参与实体之间的任何关系,因此它们不能包含外键

关于ef-code-first - EF-Code First 复杂类型的导航属性外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065466/

相关文章:

c# - Entity Framework - 如何避免查询重新编译?

C# 泛型传递具有相同属性的不同对象

c# - 检查 EF 语句中的空实体

Asp.net Core Linq 查询花费太多时间

mysql - 如何在 mvc4 代码优先应用程序中使用 MySQL 成员资格?

c# - 无法首先使用实体​​框架代码将列表保存到数据库中

mysql - 尝试使用 Mysql.Data.Entity 时出现异常

entity-framework - EF Core 3 具有值(value)生成器

c# - Entity Framework ,自动应用迁移

c# - Entity Framework 插入多对多现有 parent 的记录