我目前在blazor应用程序中有一个服务和一个blazor组件,该组件从数据库视图中检索数据并允许用户更新数据。大!这是下一页。现在,我还有很多可以做相同的事情。在我的项目中,每个数据库视图都有一个模型。
我的问题是,是否需要为每个模型创建服务?当然,有一种方法可以提供某种通用服务,其中一个人可以简单地传入模型进行交互。我不太确定应该在网上寻找帮助的内容。如果有人甚至可以将我指向正确的方向,我将不胜感激。
代码设置
namespace AdministrationWebApplication.Models.Settings
{
public partial class FlowSettingsView
{
public byte SettingId { get; set; }
public string SettingName { get; set; }
public object SettingValue { get; set; }
}
}
namespace AdministrationWebApplication.Data
{
public partial class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public virtual DbSet<FlowSettingsView> FlowSettingsView { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
...
}
...
}
namespace AdministrationWebApplication.Services
{
public class DataService
{
protected ApplicationDbContext _context { get; private set; }
public DataService(ApplicationDbContext context)
{
_context = context;
}
}
}
namespace AdministrationWebApplication.Services
{
public class SettingsService : DataService
{
public SettingsService(ApplicationDbContext context) : base(context) {}
public async Task<List<FlowSettingsView>> GetSettingsAsync()
{
return await _context.FlowSettingsView.ToListAsync();
}
public async Task<int> UpdateSettingsAsync(List<FlowSettingsView> flowSettingsView)
{
_context.FlowSettingsView.UpdateRange(flowSettingsView);
return await _context.SaveChangesAsync();
}
}
}
要了解我想做什么,请查看以下版本的服务类:
namespace AdministrationWebApplication.Services
{
public class GenericDataService : DataService
{
AnyModel _anyModel;
public GenericDataService(ApplicationDbContext context, AnyModel anyModel) : base(context)
{
_anyModel = anyModel;
}
public async Task<List<AnyModel>> GetDataAsync()
{
return await _context.AnyModel.ToListAsync();
}
public async Task<int> UpdateAnyModelAsync(List<AnyModel> anyModel)
{
_context.AnyModel.UpdateRange(anyModel);
return await _context.SaveChangesAsync();
}
}
}
答案 0 :(得分:1)
代替此
public async Task<List<AnyModel>> GetDataAsync()
{
return await _context.AnyModel.ToListAsync();
}
您可以使用
public async Task<List<T>> GetDataAsync<T>()
{
return await _context.Set<T>().ToListAsync();
}
(或将其<T>
移至全班级)。