如何解决使用Linq建立关系,数据库中不存在任何关系
我一直使用.Net Core Linq表达式.Include
和.ThenInclude
在我的Entity Framework Core项目中取得了巨大的成功。
但是,我需要合并数据库中没有任何关系的2种模型。
我的SQL查询如下:
SELECT * FROM selectedEnzymes se
LEFT JOIN enzymeDeFinitions ed ON se.selectedEnzymeID = ed.selectedEnzymeID
WHERE se.ecosystemID = 7
selectedEnzymes 和 enzymeDeFinitions 都是模型。
但是,即使它们都包含 selectedEnzymeID ,它们之间也没有关系。在数据库中,没有密钥。
所以我在想,如果不存在关系,是否可以使用Linq以这种方式组合两个模型?
谢谢!
解决方法
您可以像在SQL中一样使用LINQ Join and Select。
从这样的模型和两个类的列表开始:
public class SelectedEnzymes
{
public int SelectedEnzymeId { get; set; }
public int EcosystemId { get; set; }
public string OtherPropertySelectedEnzymes { get; set; }
}
public class EnzymeDefinitions
{
public int SelectedEnzymeId { get; set; }
public string OtherPropertyEnzymeDefinitions { get; set; }
}
List<SelectedEnzymes> selectedEnzymesList = new List<SelectedEnzymes>();
List<EnzymeDefinitions> enzymeDefinitionList = new List<EnzymeDefinitions>();
您可以执行以下操作:
var query = selectedEnzymesList // table in the "FROM"
.Join(enzymeDefinitionList,// the inner join table
selected => selected.SelectedEnzymeId,// set the First Table Join parameter key
definition => definition.SelectedEnzymeId,// set the Secont Table Join parameter key
(selected,definition) => new { SelectedEnzyme = selected,EnzymeDefinition = definition }) // selection -> here you can create any kind of dynamic object or map it to a different model
.Where(selectAndDef => selectAndDef.SelectedEnzyme.EcosystemId == 7); // where statement
,
所以我想知道,有没有办法使用Linq来组合两个模型 如果没有关系,以这种方式?
实际上,这类似于获取两个相关表的方法。
您可以直接使用以下linq来实现:
var data = (from se in _context.SelectedEnzymes
join ed in _context.EnzymeDefinitions
on se.SelectedEnzymeId equals ed.SelectedEnzymeId
where se.EcosystemId == 7
select new { se.Name,se.LocationId,ed.Name,ed.CountryId }).ToList();
这是结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。