Asp.net mvc 3 FindBy方法实体框架
我有以下帐户模式: 这个存储库类: 我得到了这个错误: 我调用GetAccountBy的操作如下:Asp.net mvc 3 FindBy方法实体框架,asp.net-mvc-3,entity-framework,Asp.net Mvc 3,Entity Framework,我有以下帐户模式: 这个存储库类: 我得到了这个错误: 我调用GetAccountBy的操作如下: public ActionResult Edit(Guid accountId) { var account = _accountService.GetAccountBy(accountId); return View(account); } 这有什么问题?非常感谢您的帮助。如错误消息所示,您只能使用System.
public ActionResult Edit(Guid accountId)
{
var account = _accountService.GetAccountBy(accountId);
return View(account);
}
这有什么问题?非常感谢您的帮助。如错误消息所示,您只能使用System.Int32和System.Guid调用DbSet.Find(params object[]keyValues)方法。(井和System.Decimal、System.DateTime可能用于复合键) 该方法不会在您的模型中查找Id或PK并自动使用它(当您传递Account时,该方法不会使用Account.Id)-因为它使用“主键值” 考虑按照中的建议传递谓词 如果您的模型始终具有Guid类型的Id,那么您可以直接传递Id:
public T FindBy(T entity)
{
return _entitySet.Find(entity.Id);
}
希望这有帮助。您没有正确调用
DBSet.Find()
方法
你需要通过考试
要查找的实体的主键的值
您不传入实体的实例,而是传入标识实体的键值。根据您的示例,您不需要创建account的新实例:
var account = new Account(accountId);
_unitOfWork.AccountRepository.FindBy(account);
您只需将accountId
传递给FindBy()
以下是您的代码修订:
public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
{
private readonly DbSet<T> _entitySet;
public T FindBy(params Object[] keyValues)
{
return _entitySet.Find(keyValues)
}
}
public AccountViewModel GetAccountBy(Guid accountId)
{
_unitOfWork.AccountRepository.FindBy(accountId);
var accountView = account.ConvertToAccountView();
return accountView;
}
公共类存储库:i存储库,其中T:class,IAggregateRoot
{
私有只读数据库集_entitySet;
公共T FindBy(参数对象[]键值)
{
返回_entitySet.Find(keyValues)
}
}
公共帐户视图模型GetAccountBy(Guid accountId)
{
_unitOfWork.AccountRepository.FindBy(accountId);
var accountView=account.ConvertToAccountView();
返回帐户视图;
}
在开始新问题之前,编辑现有问题的可能重复项
public ActionResult Edit(Guid accountId)
{
var account = _accountService.GetAccountBy(accountId);
return View(account);
}
public T FindBy(T entity)
{
return _entitySet.Find(entity.Id);
}
var account = new Account(accountId);
_unitOfWork.AccountRepository.FindBy(account);
_unitOfWork.AccountRepository.FindBy(accountId);
public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
{
private readonly DbSet<T> _entitySet;
public T FindBy(params Object[] keyValues)
{
return _entitySet.Find(keyValues)
}
}
public AccountViewModel GetAccountBy(Guid accountId)
{
_unitOfWork.AccountRepository.FindBy(accountId);
var accountView = account.ConvertToAccountView();
return accountView;
}