简体   繁体   中英

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.

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. I must use this query as a stored procedure in my project.

C# code:

var result = dbContext.Database.SqlQuery<TbA>("sp_1");

EF entity class :

[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. The class will contain the attributes you which to return.

Second Use LINQ queries example.

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.

Also if you want to use the class created with option 1, the select section of the query changes to

select new TbAandTbB{
    attr1 = tba.attr1,
    attr2 = tbb.attr1
    // and so on
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM