创建一个可以访问许多不同上下文数据库表的通用方法

Create one generic method that can access many different context database tables

我有一堆名称如下的方法:

GetMonsterName
GetTreasureName
GetSpiritName
GetCharacterName

他们都做几乎相同的事情...就像这个例子:

public async Task<string> GetMonsterName(long id)
{
    var type = await _context.MonsterType.FindAsync(id);
    return type.Name;
}

我知道您可以将 <T> 用于泛型 return 类型,但是有没有办法同时为我需要访问的数据库 table 传入泛型类型?

这样我就可以这样使用它了?

var type = await _context.<WhateverDatabaseTable>.FindAsync(id);

这样我就不需要每次想从数据库中获取一些东西时都编写新方法了?

谢谢!

我自己通常使用通用数据访问 class(类似存储库)来消除重复代码,这里的一个主要 EF 函数是 Set<> 方法,它为我们提供 table by entity通用参数:

一个简单的例子是:

public async Task<T> GetAsync<T>(long id) where T : class
{
    var item = await context.Set<T>().FindAsync(id);
    return item;
}

使用这个方法会是这样的:

var item = GetAsync<Partner>(123);

要获得 Name 道具,我们应该创建一个基础 class,所有实体都接受它作为晚餐 class :

public class Entity
{
    public string Name { get; set; }
}

更改基数class:

public class Device : Entity

并将我们的通用函数更改为:

public async Task<string> GetAsync<T>(long id) where T : Entity
{
    var item = await context.Set<T>().FindAsync(id);
    return item.Name;
}

终于得到名字:

string deviceName = await GetNameAsync<Device>(1);