2013-02-14 119 views
1

我有这个帐户型号FindBy方法实体框架

public class Account :IAggregateRoot 
    { 
     public Account() 
     { 
     } 
     public Account(Guid accountId) 
     { 
      Id = accountId; 
     } 

     public Guid Id { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string Email { get; set; } 
     } 
} 

仓储类

public class Repository<T> : IRepository<T> where T : class, IAggregateRoot 
    { 

     private readonly DbSet<T> _entitySet; 

     public T FindBy(T entity) 
     { 
      return _entitySet.Find(entity); 
     } 
    } 

,现在当我想通过标识实体,例如:

public AccountViewModel GetAccountBy(Guid accountId) 
     { 
      var account = new Account(accountId); 
      _unitOfWork.AccountRepository.FindBy(account); 
      var accountView = account.ConvertToAccountView(); 
      return accountView; 
     } 

我拿到了这个错误

The specified parameter type is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported. 

我的行动来呼吁GetAccountBy是这样的:

public ActionResult Edit(Guid accountId) 
     { 
      var account = _accountService.GetAccountBy(accountId); 
      return View(account); 
     } 

是什么问题呢?任何帮助深表感谢。

+0

可能在[EntityFramework中的FindBy Id方法]重复(http://stackoverflow.com/questions/14865013/findby-id-method-in-entityframework) – Jehof 2013-02-14 12:06:49

+0

编辑你的存在在开始新问题之前提出问题 – Jehof 2013-02-14 12:07:30

回答

1

您没有正确调用DBSet.Find()方法。

As the documentation states你需要传递

主键的值的实体被发现

你不要在实例的实体传球,你在传递识别实体的的关键值。从你的例子中,你不需要创建帐户的新实例:

var account = new Account(accountId); 
_unitOfWork.AccountRepository.FindBy(account); 

你只需要通过accountIdFindBy()

_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; 
} 
1

如错误消息所示,您只能使用System.Int32和System.Guid调用DbSet.Find(params object [] keyValues)方法。 (well和System.Decimal,System.DateTime可能用于复合键)

该方法不会在您的模型中查找Id或PK并自动使用它(当您通过Account时,该方法将不会使用Account.Id ) - 作为其使用“主键值” http://msdn.microsoft.com/en-us/library/gg696418(v=vs.103).aspx

考虑通过一个谓语在FindBy Id method in EntityFramework

建议如果模型总是有类型GUID的ID,那么也许你可以直接通过编号:

public T FindBy(T entity) 
     { 
      return _entitySet.Find(entity.Id); 
     } 

希望这有助于。