C# 在泛型存储库中放置字符串而不是Id的方法
我有一个用于PUT的通用存储库方法,它运行良好,在这里它通过主键Id的EF的通用方法找到。C# 在泛型存储库中放置字符串而不是Id的方法,c#,entity-framework,generics,asp.net-web-api,repository-pattern,C#,Entity Framework,Generics,Asp.net Web Api,Repository Pattern,我有一个用于PUT的通用存储库方法,它运行良好,在这里它通过主键Id的EF的通用方法找到。 我要寻找的是,我想根据特定列更新一条记录,并且它的值是string类型的。有可能这样做吗 public virtual TEntity GetByID(object id) { return DbSet.Find(id); } 根据您在评论中所说的,所有您的实体都有您想要查找和更新的列。大概是这样的: public class EntityBase { public string Loo
我要寻找的是,我想根据特定列更新一条记录,并且它的值是string类型的。有可能这样做吗
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();
}
}
公共类GenericRepo,其中tenty:EntityBase
{
...
public void UpdateByStringColumn(字符串lookupCol、字符串col1Value、字符串col2Value)
{
//如果希望在未找到实体的情况下将其中断,请将其更改为First并删除健全性检查
var entity=this.DbSet.FirstOrDefault(p=>p.LookupCol==LookupCol);
如果(实体!=null)
{
entity.Col1=col1Value;
entity.Col2=col2Value;
SaveChanges();
}
}
}[检查是否满足您的要求]()是的,这是可能的。那么,到目前为止你试过什么?你现在到底被困在哪里了?可能是重复的你说你想根据一个特定的列更新一个记录。这是否意味着该列将充当只更新该列的更新ir的过滤器?我尝试了完整实体更新
public virtual void update(TEntity entityToUpdate){DbSet.Attach(entityToUpdate);Context.Entry(entityToUpdate).State=EntityState.Modified;}