使用linq到实体通过SQL查询将值存储到对象的对象中

时间:2019-05-07 09:35:53

标签: c# linq linq-to-entities

我有两个sql表和两个以下类。

private List<JsonObject> info;

or

private List<String> info; //JsonString

我可以将City Master数据存储到public class StateMaster { public long StateId { get; set; } public string StateName { get; set; } } public class CityMaster { public string CityName { get; set; } public long CityId { get; set; } public StateMaster objStateMaster { get; set;} } 对象中,但是如何将State Master数据存储到CityMaster对象中,就像已经在City Master类中创建的objStateMaster对象一样。

City Master

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是创建一个名为StateCityMaster的新类,如下所示:

public class StateCityMaster
{
    public string CityName { get; set; }
    public long CityId { get; set; }
    public long StateId { get; set; }
    public string StateName { get; set; }
}

而不是将查询编辑为:

List<StateCityMaster> objStateCityMaster = dbContext.Database.SqlQuery<StateCityMaster>(
$@"select 
    CM.CityName,
    CM.CityId,
    SM.StateId,
    SM.StateName
from CityMaster CM
left join StateMaster SM
    On SM.StateId= CM.StateId").ToList();

然后创建CityMaster对象的列表并复制值:

List<CityMaster> citiesMaster = new List<CityMaster>();

objStateCityMaster.forEach(scm => citiesMaster.Add(new CityMaster()
{
    CityName = scm.CityName;
    CityId = scm.CityId;
    objStateMaster.StateId = scm.StateId;
    objStateMaster.StateName = scm.StateName;
}));