EF-Code First navigation property foreign key in complex type

ef-code-first entity-framework-6

Question

I have complex type for Audit fields

My complex type:

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

My base Entity (all other inherti this one) has AuditData property:

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
}

I have 2 navigation properties CreatorUser and ModifierUser. I know you cant have navigation property in ComplexType but can my navigation property on entity be mapped with foreign key in complexType

something like:

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

becouse CreatorUserId will be property in every entity but EF is not aware of it. Mybe there is solution in fluent API ?

1
6
10/11/2015 1:22:14 PM

Accepted Answer

The official documentation says:

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.

It follows that that complex types can not participate in any relations among entities, so they can't contain foreign keys

3
10/14/2015 3:57:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow