c# Entity Framework - 泛型解决方案

标签 c# entity-framework generics

是否有针对以下代码的泛型解决方案?

public static int SaveReorder(IList<int> listItems)
    {
        int result = 0;
        int order = 1;
        Entity1 db = null;

        using (ObjectContext context = new ObjectContext())
        {
            foreach (int id in listItems)
            {
                db = Get(context, id);
                db.Order = order;
                context.SaveChanges();
                order += 1;
            }
            result = 1;
        }
        return result;
    }

listItems 包含一个有序的 identitykeys 序列。 Entity1 是我们的 EDM 中的 EntityObjects 之一。 Get(...) 是同一个类中的自定义方法,用于根据当前 ObjectContext 和 Id 获取 EntityObject。

我们需要一个用于此实现的通用解决方案,以便我们可以将其应用于多个 EntityObject,其中属性“Order”是所有 EntityObject 的公共(public)属性。这可能吗?

最佳答案

我想到了两个选项,正如 Akash 已经建议的那样:

  • 要么让实体实现具有“订单”属性的接口(interface):

    interface IEntityOrder { int Order { get;放; }

    部分类 Entity1 : EntityObject { }

    partial class Entity1 : IEntityOrder { public int Order { get;放; }

  • 或者使用反射来设置“Order”属性的值(如果它是一个字段,则为 FieldInfo):

    PropertyInfo pi = db.GetType().GetProperty("订单");

    pi.SetValue(db, newValue, null);

关于c# Entity Framework - 泛型解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1350765/

相关文章:

generics - Kotlin "out"和 "in"和泛型 - 正确使用

C# 类型转换错误尽管通用约束

c# - 重载方法以支持引用类型和可空类型

c# - 什么是 DetailsView.EnableModelValidation?

c# - 使用 Entity Framework 5 Code-First 和 POCO 实现 N 层数据层?

c# - 向所有查询 Entity Framework 添加过滤器

java - 当构造函数初始化参数时从泛型类创建实例

c# - 如何在 MVVM WPF 的主窗口中打开子窗口

c# - XSD 模式到 COM 接口(interface)

c# - 如何使用 Entity Framework 6 选择包含字符串中任何单词的项目?