简体   繁体   中英

Entity Framework Core 3 - model with some fields from a stored procedure

In EF Core 3, I have a model where only a few fields of the model will be retrieved from a legacy stored procedure. The stored procedure has about 300 lines of business logic built into it, so we're not keen on moving the logic out of the stored procedure due to testing efforts.

It doesn't appear that executing the stored procedure inside the get is the right approach here (it causes an InvalidOperation exception). What's the right way to link the columns that come out of the stored procedure into the existing model?

The only other way I've thought of was possibly filling those fields in on the load property of the page; but maybe there's another way I'm missing that's better. :)

// This is my existing display model
internal partial class MyExistingModel
{
    [Key]
    public int id{ get; set; }
    public int R_Id { get; set; }
    public string G_Number { get; set; }

    public virtual P1 ParentRuns { get; set; }
    public virtual ICollection<P1> AnotherOne { get; set; }
}

This is the stored procedure header which is called for each MyExistingModel.id :

get_ComplicatedLogicStuff(@in_id)
AS
    SELECT 
        column1, column2, column3, column4
    ... 
    WHERE
        table1.id = @in_id;

Thanks!

Instead of putting that logic in the page I would create a ModelService class to load the model for you. Then you can specifically choose how to load your navigation properties. Here is an approach you could use.

internal class MyExistingModelService 
{
    public IEnumerable<MyExistingModel> List () 
    {
        using ( var context = new YourDataContextHere() ) {
            return context.MyExistingData
                .Select ( myExistingData => new MyExistingModel () {
                    Id = myExistingData.Id,
                    R_Id = myExistingData.R_Id,
                    AnotherOne = context.YourStoredProcedure().Where( (entity) => SomeFilter)   
                });
        }
    }
}

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