从性能的角度来看,检查数据库中是否存在对象的最佳方法是什么?我正在使用Entity Framework 1.0(ASP.NET 3.5 SP1).
Generics是否可以在不知道类型的情况下从我的EntityFramework中获取对象?
我正在考虑以下方面的事情:
public T GetObjectByID<T>(int id)
{
return (from i in myDatabase.T where i.ID == id select i);
}
Run Code Online (Sandbox Code Playgroud)
那可行吗?我可以使用Reflection以某种方式将T.GetType().Name其用于表中吗?
编辑
另一个问题是,并非所有可用的表都使用"ID"作为其唯一的列名.
给出以下代码:
void MergeDbContext(DbContext aSourceDbContext, DbContext aDestinationDbContext)
{
var sourceEntities = aSourceDbContext.ChangeTracker.Entries().ToList();
foreach (DbEntityEntry entry in sourceEntities)
{
object entity = entry.Entity;
entry.State = EntityState.Detached;
// check if entity is all ready in aDestinationDbContext if not attach
bool isAttached = false;// TODO I don't know how to check if it is all ready attched.
if (!isAttached)
{
aDestinationDbContext.Set(entity.GetType()).Attach(entity);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我如何一般性地确定实体是否存在于上下文中.
我有一个场景,我必须更新一个实体,如果它存在或添加一个新实体,如果它不存在.
我想为此执行一个单独的方法(如果它只是一次访问服务器就会很棒).
EF中有类似的东西吗?
现在我的代码看起来像这样:
var entity = db.Entities.FirstOrDefault(e => e.Id == myId);
if (entity == null)
{
entity = db.Entities.CreateObject();
entity.Id = myId;
}
entity.Value = "my modified value";
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
但我想避免第一个查询,如下所示:
var entity = new Entity();
entity.Id = myId;
entity.Value = "my modified value";
db.AddOrAttach(entity);
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
有类似的东西吗?或者我必须执行第一个查询,不管是什么?
谢谢
我正在开发一个Asp.Net MVC应用程序,我正在尝试编写一个通用方法来检查DB中是否存在实体,或者使用传递的entityId来实现此方法.如下所示:
public bool CheckIfUserExistsByUserId(int userId)
{
return _userRepository.DbSet().Any(u => u.Id == userId);
}
Run Code Online (Sandbox Code Playgroud)
但是此方法仅检查_userRepository并接受整数作为entityId.
我的问题是我想把这个泛型方法作为我的BaseService中的一般方法,就像我在下面写的其他常规方法一样:
public class BaseService<TModel> : IBaseService<TModel> where TModel : class
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBaseRepository<TModel> _baseRepository;
public BaseService(IUnitOfWork unitOfWork, IBaseRepository<TModel> baseRepository)
{
_unitOfWork = unitOfWork;
_baseRepository = baseRepository;
}
public BaseService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public void Add(TModel entity)
{
this._baseRepository.Add(entity);
}
public void Remove(TModel entity)
{
this._baseRepository.Remove(entity);
}
/// <summary>
/// Remove All Provided Items At Once …Run Code Online (Sandbox Code Playgroud) asp.net ×2
c# ×2
asp.net-mvc ×1
dbcontext ×1
exists ×1
generics ×1
linq ×1
optimization ×1
reflection ×1
sql ×1
sql-update ×1