如何映射具有对实体的引用的值类型?

Ken*_*eth 14 .net c# entity-framework entity-framework-5

我在实体框架中遇到了映射问题.

我有以下课程(简化):

public class Building
{

    public int ID { get; set; }     
    // *.. snip..* other properties
    public Location Location { get; private set; }
}

public class Location
{
    public string Street {get; set;}
    public Country country {get; set}
}
public class Country
{
    public int ID { get; set; } 
    public string Name { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

Building和Country是实体,它们保存在数据库中.位置是值类型,应映射到与Building相同的表.

但是,当我以这种方式映射它时,实体框架也希望将Location映射到一个表,并抱怨它没有Key.我不想给它一把钥匙,因为它属于建筑物,根本不应该是一个实体.

我已经看到了一些解决方法,说你需要将Country放在Building-class上,但这感觉不好(并且在语义上是完全错误的).

我正在使用Entity Framework 5

Dev*_*yal -3

您可以使用 [NotMapped] 属性标记 Building 类中的 Location 属性。

using System.ComponentModel.DataAnnotations.Schema;
public class Building
{
    [NotMapped]
    public Location Location { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

希望能解决您的问题!