【问题标题】:Entity Framework Core 3 - model with some fields from a stored procedureEntity Framework Core 3 - 具有来自存储过程的一些字段的模型
【发布时间】:2020-03-17 12:40:33
【问题描述】:

在 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-framework ef-code-first ef-core-3.0


    【解决方案1】:

    我不会将该逻辑放在页面中,而是创建一个 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)   
                    });
            }
        }
    }
    

    【讨论】:

    • 谢谢,差不多结束了。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    相关资源
    最近更新 更多