本文介绍了从不同表返回公共字段的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大约有15个正在使用的表,并且正在为这些表创建审计报告.所有这些表都有一个UserId列,该列将使用进行更改的最后一个用户的ID更新.我想创建一个存储库方法,该方法允许我传递要用于该方法的表实体,然后仅返回要在审核页面上使用的UserId列表,而不是允许用户在其中键入任何内容在用于审核的UserId搜索字段中,我只想提供一个下拉列表,其中只包含我传递给该方法的表中的userId.

I have around 15 tables that I am working with, and I am working on creating audit reports for these tables. All of these tables have a UserId column that gets updated with the last user's Id that made changes. I would like to create a repository method that would allow me to pass in what table entity to use for the method and then just return a list of the UserIds to use on the audit page, instead of allowing the user to type whatever they want in the UserId search field for the audit, I want to supply a dropdown with only the userIds that are in the table that I pass to the method.

我在想这样的事情:

var ids = _repo.GetUserIds(//table entity here, unsure how to declare in signature);

推荐答案

您需要制作一个通用方法,使用一个表示您的类型实体的类型参数,并访问相应的 DbSet< T> 从该集合中获取数据.

You need to make a generic method, with a type parameter that represents your type entity and access the corresponding DbSet<T> to get the data from that collection.

public int GetUserId<TEntity>()
{
   int userId;
   using (var cts = new MyDbContext())
   {
      userId = ctx.DbSet<TEntity>.FirstOrDefault().Select(e => e.UserId);
   }
   return userId;
}

为了能够包含投影lambda e =>e.UserId ,您需要使所有类都实现这样的接口:

To be able to include the projection lambda e => e.UserId you need to make all your classes implement an interface like this:

public interface IUserId
{
  public int UserId { get; set; }
}

并且您的泛型类必须具有相应的类型约束:

And your generic class must have the corresponding type constraint:

public RepoClass<T>
   where T:IUserId
{
    // Define the generic method here
}

这篇关于从不同表返回公共字段的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:11