如何将SQL数据库结果映射到EF Core中的域模型

时间:2018-08-23 16:25:57

标签: .net entity-framework .net-core ef-core-2.0

我有以下域模型:

once

必须用于填充这些模型的数据库视图返回一个平面列表,如下所示:

enter image description here

我希望为DbContext配置实体,以便为这些国家划分省份。

我可以创建一个与数据库结果匹配的域模型,尽管我真的很想将域模型与其在特定数据库中的表示方式分开-尤其是在数据库更改的情况下。

像这样可能吗?如果是这样,它将如何实施?

public class Country
{
    public string ISOAlpha3Code { get; set; }
    public string NameUS { get; set; }

    public string NameES { get; set; }
    public string NameFR { get; set; }

    public List<Province> Provinces { get; set; }
}

public class Province
{
    public string Code { get; set; }
    public string NameUS { get; set; }

    public string NameES { get; set; }
    public string NameFR { get; set; }
}

1 个答案:

答案 0 :(得分:0)

可以稍微调整模型以适应重复的小组。

public class Country {
    public string ISOAlpha3Code { get; set; }
    public virtual ICollection<Name> Names { get; set; }
    public virtual ICollection<Province> Provinces { get; set; }
}

public class Province {
    public string Code { get; set; }
    public string ISOAlpha3Code { get; set; }  // FK to Country
    public virtual ICollection<Name> Names { get; set; }
}

public class Name {
    public string ISOAlpha3Code { get; set; }  // FK to Country
    public string Code { get; set; }           // FK to Province, null for country names
    public string Language { get; set; }       // US-EN, etc.
    public string NameField { get; set; }
}

当然,所有这些都假定一旦输入数据便是不可变的,否则,如果关键数据可能更改(ISOAlpha3Code,Code),则使用替代PK / FK添加和维护关系。而且我会确保为NameField生成了NVARCHAR,因为您将要存储Unicode字符串。