2016-05-13 40 views
1

我有兩個班,其來自一個庫,即不能由我來改變:地圖只有一個子屬性

public class EntityInfo 
{ 
    public Guid Id { get; set; } 
    //... some other properties 
} 
public class MyEntity 
{ 
    public Guid MyEntityId { get; set; } 
    public EntityInfo AnotherEntityInfo { get; set; } 
    //... some other properties 
} 

我需要myEntity所與這些列映射到表:

MyEntityId uniqueidentifier, 
AnotherEntityId uniqueidentifier -- Here the value of AnotherEntityInfo.Id should be mapped 
-- ... some other properties 

我不需要映射類型EntityInfo的其他屬性,只是Id。所以它就像是扁平化EntityInfo並只取其Id。再次,我不能更改類MyEntity和EntityInfo

有沒有人知道這樣做的方式?

+0

兩個類到一個表。這是表分裂或複雜類型。這取決於您可以做的主要關鍵要求。也許你可以看看這些關鍵詞。 –

回答

1

您需要爲類myEntity所如更新ForeignKey的:

public class MyEntity 
{ 
    public Guid MyEntityId { get; set; } 
    [ForeignKey("AnotherEntityInfo")] 
    public int AnotherEntityInfoId { get; set; } 
    public EntityInfo AnotherEntityInfo { get; set; } 
    //... some other properties 
} 

你可以在這裏閱讀:再次source

+0

我做了這個和選擇工作,例如:MyEntities.FirstOrDefault(x => x.AnotherEntityInfo.Id == id)。數據庫中的選擇是正確的,但AnotherEntityInfo屬性在生成的MyEntity對象中爲null。 – Vladimir

+0

還有一件事:AnotherEntityInfo沒有保存在數據庫中,它就像一個「複雜類型」,其中只有一個屬性被保存,並直接保存在MyEntity表中。 – Vladimir

1

,我不能改變的類myEntity所和EntityInfo

然後Fluent configuration是您擁有的唯一選擇。

如下重寫你的DbContext派生類OnModelCreating方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<MyEntity>() 
     .HasRequired(e => e.AnotherEntityInfo) 
     .WithMany() 
     .Map(c => c.MapKey("AnotherEntityInfoId")); 

    base.OnModelCreating(modelBuilder); 
} 

編輯:我誤解了這個問題。如果EntityInfo不是一個實體,一般是隻MyEntity,那麼你可以使用下面的流暢配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    // Ignore all the properties except Id  
    modelBuilder.ComplexType<EntityInfo>() 
     .Ignore(e => e.Property1) 
     .Ignore(e => e.Property2) 
     ... 
     .Ignore(e => e.PropertyN); 

    base.OnModelCreating(modelBuilder); 
} 

以上將在MyEntity表中創建AnotherEntityInfo_Id列。我沒有找到指定列名的方法。