EF Core-多重拥有类型对应问题

时间:2018-07-02 09:37:20

标签: entity-framework-core

我想问一下在EntityFramework Core-v 2.1中构建模型的问题。 首先要做的事情-我要实现的目标如下:

//  I want this entity to be stored in database, with EntityReferences as owned records, 
//  stored within the same table.
//  There will be more properties of type EntityReference.
public partial class CdiEmailEvent
{
    public override Guid Id { get; set; }
    public EntityReference CdiAccountId
    public EntityReference CdiAutomationId
}

//  EntityReference is a pointer to record, containing Id of target record and it's type.
//  So Id does not point to CdiEmailEntity record, but for example an Account or Contact.
//  I want this to be an owned record within CdiEmailEvent.
public sealed class EntityReference : IExtensibleDataObject
{
    public Guid Id { get; set; }
    public string LogicalName { get; set; }
    public string Name { get; set; }
    public string RowVersion { get; set; }
}

因此实际数据可能如下所示:

new CdiEmailEvent {
    Id = "18640407-1A44-430A-8267-96BD23CC9EE8",

    CdiAccountId = new CdiAccountId {
        Id = "FBBB4932-C74C-47CE-8D1B-909C5975D945",
        Name = "Account",
        LogicalName = "cdi_account"
    },

    CdiAutomationId = new CdiAccountId {
        Id = "5496BC1C-C5FD-4AFB-B6D9-913DD5549C13",
        Name = "Automation",
        LogicalName = "cdi_automation"
    },

    ...
}

我希望数据库表看起来像这样:

Id                                      |   CdiAccountId                            |   CdiAccountName  |   CdiAccountLogicalName   |   CdiAutomationId                         |   CdiAutomationName   |   CdiAutomationLogicalName
"18640407-1A44-430A-8267-96BD23CC9EE8"  |   "FBBB4932-C74C-47CE-8D1B-909C5975D945"  |   "Account"       |   "cdi_account"           |   "5496BC1C-C5FD-4AFB-B6D9-913DD5549C13"  |   Automation          |   "cdi_automation"

我当前的模型配置是:

modelBuilder
    .Entity<CdiEmailEvent>(entity =>
    {
        entity.HasKey(e => e.CdiEmailEventId);

        entity.OwnsOne(rel => rel.CdiAccountId);
        entity.OwnsOne(rel => rel.CdiAutomationId);

        ...

        entity.ToTable("CdiEmailEvents", this._databaseConfig.DatabaseSchema);
    });

我遇到的问题是:

System.InvalidOperationException: 'The entity of type 'CdiEmailEvent' is sharing
 the table 'replication.CdiEmailEvents' with entities of type 
'CdiEmailEvent.CdiAutomationId#EntityReference', but there is no entity of this
 type with the same key value '{CdiEmailEventId: 8a99d6ab-cd82-4eb8-b548-50d903d6f26c}' 
that has been marked as 'Added'.'

我猜想EF Core正在尝试使用CdiAutomationId作为对CdiEmailEvent的引用。有谁知道我该如何改变这种行为,并强制EF Core将CdiAutomationId简单地视为没有任何键的对象?我浏览了EF Core的文档,但这在这方面不是很描述。

0 个答案:

没有答案
相关问题