[英]Can I convert stored procedure join result by SQLQuery into a form of EF ORM?
I need to convert the result of a SQL stored procedure into EF ORM. 我需要将SQL存储过程的结果转换为EF ORM。
The stored procedure contains a query like this : 该存储过程包含如下查询:
select *
from TbA
join TbB on TbA.aId = TbB.aId`
It works, but in ORM mode, the contents of TbB doesn't appear in the object that is returned. 它可以工作,但是在ORM模式下,TbB的内容不会出现在返回的对象中。 I must use this query as a stored procedure in my project.
我必须将此查询用作项目中的存储过程。
C# code: C#代码:
var result = dbContext.Database.SqlQuery<TbA>("sp_1");
EF entity class : EF实体类别:
[Table("TbA")]
public partial class TbA
{
public TbA()
{
TbB = new HashSet<TbB>();
}
[Key]
public long aId { get; set; }
[StringLength(10)]
public string rNo { get; set; }
public virtual ICollection<TbB> TbB { get; set; }
}
public partial class TbB
{
[Key]
public long rowId { get; set; }
public long aId { get; set; }
[StringLength(10)]
public string kKey { get; set; }
public virtual TbA TbA { get; set; }
}
I think you can go with any of this two options 我认为您可以选择这两个选项中的任何一个
First , Create a class that contains both attributes from TbA and TbB since you are using join. 首先 ,由于您正在使用联接,因此创建一个同时包含TbA和TbB属性的类。 The class will contain the attributes you which to return.
该类将包含要返回的属性。
Second Use LINQ queries example. 第二次使用LINQ查询示例。
var queryResult = from tba in dbContext.TbA
join tbb in database.TbB on tba.aId equals tbb.aId
select new {
//construct your class here as dynamic objects
TbA.attr1 = tba.attr1,
Tbb.attr1 = tbb.attr1
// and so on
}
queryResult
will assume any class selected in the select statement. queryResult
将假定在select语句中选择的任何类。
Also if you want to use the class created with option 1, the select section of the query changes to 另外,如果要使用通过选项1创建的类,查询的select部分将更改为
select new TbAandTbB{
attr1 = tba.attr1,
attr2 = tbb.attr1
// and so on
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.