1

私はこのアカウントモデルを持っています:

 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);
        }
     }

そして今、たとえば Id でエンティティを取得したいとき:

 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);
        }

これには何が問題ですか?どんな助けでも大歓迎です。

4

2 に答える 2

1

エラー メッセージが示すように、DbSet.Find(params object[] keyValues) メソッドは System.Int32 と System.Guid でのみ呼び出すことができます。(まあ、System.Decimal、System.DateTimeはおそらく複合キー用です)

このメソッドは、Model で Id または PK を検索して自動的に使用することはありません (Account を渡すと、メソッドは Account.Id を使用しません)。これは、「主キーの値」http://msdn.microsoft を使用するためです。 com/en-us/library/gg696418(v=vs.103).aspx

EntityFramework のFindBy Id メソッドで提案されている述語を渡すことを検討してください

モデルが常にタイプ Guid の Id を持っている場合は、ID を直接渡すことができます。

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

お役に立てれば。

于 2013-02-14T13:37:12.163 に答える
1

DBSet.Find()メソッドを正しく呼び出していません。

ドキュメントに記載されているように、合格する必要があります

検索するエンティティの主キーの値

エンティティのインスタンスを渡すのではなく、エンティティを識別するキー値を渡します。あなたの例から、アカウントの新しいインスタンスを作成する必要はありません:

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

に渡すだけaccountIdですFindBy()

_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;
}
于 2013-02-14T13:38:15.260 に答える