[英]EF Core Generic Repository get Id from new inserted generic entity async
目標:通過使用異步與 ASP.NET 核心獲取插入的通用實體的 id
問題:為了實現目標,我缺少什么部分?
代碼:
public async Task<int> AddAsync(T entity)
{
if (entity == null)
{
throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
}
try
{
await _context.AddAsync(entity);
await _context.SaveChangesAsync();
return <Id Here>
}
catch (Exception)
{
throw new Exception($"{nameof(entity)} could not be saved");
}
}
謝謝!
使用id是不行的。
使用 where T 不起作用。
您可以使用 Id 屬性創建一個接口,並讓您的所有實體實現它們。
public interface IEntity
{
public int Id { get; set; }
}
並在通用 class 中添加 where 子句。
public class GenericRepository<T> where T : IEntity
{
public async Task<int> AddAsync(T entity)
{
if (entity == null)
{
throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
}
try
{
await _context.AddAsync(entity);
await _context.SaveChangesAsync();
return entity.Id;
}
catch (Exception)
{
throw new Exception($"{nameof(entity)} could not
be saved");
}
}
}
也許嘗試使用反射:
return (int)entity.GetType().GetProperty("Id").GetValue(entity, null);
假設每個表的命名都是Id
。 否則,也許您可以將道具的名稱作為參數傳遞:
public async Task<int> AddAsync<T>(T entity, string paramName) where T : class
{
// ...
return (int)entity.GetType().GetProperty(paramName).GetValue(entity, null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.