在通用存储库中放置字符串而不是 Id 的方法
Put method for string instead of Id in generic repository
我有一个用于 PUT 的通用存储库方法,它工作正常,在这里它通过主键 ID 的 EF 通用方法找到。
我正在寻找的是我想根据特定列更新记录并且它的值是字符串类型。有没有可能做到这一点?
public virtual TEntity GetByID(object id)
{
return DbSet.Find(id);
}
根据您在评论中所说的内容,您的所有实体都有您想要查找和更新的列。像这样:
public class EntityBase
{
public string LookupCol { get; set; }
public string Col1 { get; set; }
public string Col2 { get; set; }
}
假设这是真的,您可以执行以下操作:
public class GenericRepo<TEntity> where TEntity : EntityBase
{
...
public void UpdateByStringColumn(string lookupCol, string col1Value, string col2Value)
{
//if you want it to break in case no entity was found, change it to First and remove the sanity check
var entity = this.DbSet.FirstOrDefault(p => p.LookupCol == lookupCol);
if (entity != null)
{
entity.Col1 = col1Value;
entity.Col2 = col2Value;
Context.SaveChanges();
}
}
}
我有一个用于 PUT 的通用存储库方法,它工作正常,在这里它通过主键 ID 的 EF 通用方法找到。
我正在寻找的是我想根据特定列更新记录并且它的值是字符串类型。有没有可能做到这一点?
public virtual TEntity GetByID(object id)
{
return DbSet.Find(id);
}
根据您在评论中所说的内容,您的所有实体都有您想要查找和更新的列。像这样:
public class EntityBase
{
public string LookupCol { get; set; }
public string Col1 { get; set; }
public string Col2 { get; set; }
}
假设这是真的,您可以执行以下操作:
public class GenericRepo<TEntity> where TEntity : EntityBase
{
...
public void UpdateByStringColumn(string lookupCol, string col1Value, string col2Value)
{
//if you want it to break in case no entity was found, change it to First and remove the sanity check
var entity = this.DbSet.FirstOrDefault(p => p.LookupCol == lookupCol);
if (entity != null)
{
entity.Col1 = col1Value;
entity.Col2 = col2Value;
Context.SaveChanges();
}
}
}