简体   繁体   English

如何制作DbSet的通用方法?

[英]How to make generic method for DbSets?

I have many simular meyhod like this two: 我有很多类似这两个类似的方法:

    public static List<MyCatalogViewModel> LoadCatalog1(...)
    {
       var catalog= DbContext.MyContexClass1.Where(t => !t.Deleted).Select(k=> new MyCatalogViewModel{ Id= k.Id, Name = k.Name}).ToList();
       return catalog;
    }

    public static List<MyCatalogViewModel> LoadCatalog2(...)
    {
       var catalog= DbContext.MyContexClass2.Where(t => !t.Deleted).Select(k=> new MyCatalogViewModel{ Id= k.Id, Name = k.Name}).ToList();
       return catalog;
    }

Here is i take data from DbContext . 这是我从DbContext获取数据。 Difference only in DBSet<> . 仅在DBSet<>DBSet<>不同。
How can i make a generic method instead of this methods? 如何制作通用方法而不是此方法?

Classes MyContexClass2 and MyContexClass1 both have a properties Id and Name . MyContexClass2MyContexClass1都具有属性IdName And looks like: 看起来像:

public partial class MyContexClass1: AccountableDbObject
{
    public MyContexClass1()
    {
      <..some code..>
    }

    public override int Id{ get; internal set; }
    public string Name { get; set; }

     <...Another properties...>
}

The DbContext has a Set<T> method that allows retrieving a set of arbitrary entities (aslong as their type is registered with the context). DbContext具有Set<T>方法,该方法允许检索一组任意实体(只要其类型已在上下文中注册)。

Update 更新资料

To actually use the properties defined on these generic types, you need the model classes to implement a common interface: 要实际使用在这些泛型类型上定义的属性,您需要模型类来实现一个公共接口:

public interface ICatalogItem { //or some other name 
      bool Deleted { get; }
      int Id { get; }
      string Name { get; }
}

Eg your MyContexClass1 definition would become 例如,您的MyContexClass1定义将变为

MyContexClass1 : AccountableDbObject, ICatalogItem

Now you can build a generic method that will return the appropriate viewmodels: 现在,您可以构建一个通用方法,该方法将返回适当的视图模型:

public static List<MyCatalogViewModel> LoadCatalog<T>()
    where T : class, ICatalogItem
{
   var catalog= DbContext.Set<T>.Where(t => !t.Deleted).Select(k=> new MyCatalogViewModel{ Id= k.Id, Name = k.Name}).ToList();
   return catalog;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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