首页 > 解决方案 > Entity Framework Core 3 - 具有来自存储过程的一些字段的模型

问题描述

在 EF Core 3 中,我有一个模型,其中仅从旧存储过程中检索模型的几个字段。存储过程内置了大约 300 行业务逻辑,因此由于测试工作,我们并不热衷于将逻辑移出存储过程。

在这里执行 get 中的存储过程似乎不是正确的方法(它会导致InvalidOperation异常)。将来自存储过程的列链接到现有模型的正确方法是什么?

我想到的唯一其他方法可能是在页面的加载属性中填写这些字段;但也许我错过了另一种更好的方式。:)

// 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; }
}

这是为每个调用的存储过程标头MyExistingModel.id

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

谢谢!

标签: c#entity-frameworkef-code-firstef-core-3.0

解决方案


我不会将该逻辑放在页面中,而是创建一个 ModelService 类来为您加载模型。然后您可以具体选择如何加载您的导航属性。这是您可以使用的一种方法。

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)   
                });
        }
    }
}

推荐阅读