2017-01-15 9 views
0

とコンストラクタは、私はクラスの従業員を作成します。コードまずEntity Frameworkの、選択ViewModelに - パラメータ

public class Employees : BaseModel 
{ 
    [Key] 
    public int EmployeeId { get; set; } 
    // [ohter parameter] 
    public int? DepartmentId { get; set; } 
    public virtual Departments Departments { get; set; } 
    public int? OccupationId { get; set; } 
    public virtual Occupations Occupations { get; set; } 
} 

私はビューモデルを作成したいです。

public class Employee_ViewModel 
{ 
    public Employee_ViewModel(Employees item) 
    { 
     this.EmployeeId = item.EmployeeId; 
     //[other parameter] 
     this.DepartmentId = item.DepartmentId; 
     this.OccupationId = item.OccupationId; 
    } 

    public int EmployeeId { get; set; } 
    //[other parameter] 
    public string DepartmentName { get; set; } 
    public string OccupationName { get; set; } 
} 

ように見えるEmployee_ViewModel返す私の方法:最後に、私はエラーを取得する

List<Employee_ViewModel> item = contex.Employees.Where(w => w.IsActive == true && w.IsVisible == true) 
            .Include(i => i.Departments) 
            .Include(i => i.Occupations) 
            .Select(s => new Employee_ViewModel(s) 
            { 
             OccupationName = s.Occupations.Name, 
             DepartmentName = s.Departments.Name 
            }) 
            .ToList(); 

Only parameterless constructors and initializers are supported in LINQ to Entities.

ソリューションは、このポストを形成する:

Only parameterless constructors and initializers are supported in LINQ to Entities

は動作していますが、なぜ私のコンストラクタは動作しませんか?

+1

例外メッセージ(**パラメータなし**)からは明らかではありません。これは何度も繰り返し尋ねられています。 –

+0

私は知っているが、私はパラメータを簡単に書き直したい。 – 18666

答えて

2

他のツールとして、Entity Frameworkは実行時にモデルのプロキシを作成し、モデルの派生クラスとして発行されます。明らかに、プロキシジェネレータがパラメータを持つコンストラクタを使用してモデルをインスタンス化することは期待できません。

要約:単純な使い方をしてください。エンティティには少なくともパラメータのないコンストラクタが含まれている必要があります。

物事をシンプルに保つためにAutoMapperの使用を検討してください:queryable extensions

// If you go for the AutoMapper approach, you need no constructor 
// with parameters or factory method anymore! 
List<Employee_ViewModel> item = contex.Employees.Where(w => w.IsActive == true && w.IsVisible == true) 
            .Include(i => i.Departments) 
            .Include(i => i.Occupations) 
            .ProjectTo<EmployeeViewModel>() 
            .ToList(); 

参照AutoMapperのドキュメントをEntity Frameworkのとそれを組み合わせる方法についての詳細を学ぶために。

+0

From関数を使用してソリューションを使用しましたが、エンティティへの_LINQエラーは、 'MS.ViewModel.Employee_ViewModel From(MS.Models.Employees)'メソッドを認識せず、このメソッドをストア式に変換することはできません._ パフォーマンスはどうですか、AutoMapperを使いますか? – 18666

+0

ToList()を先に追加問題を選択して選択します。しかし、正しい解決策はありますか? – 18666

+1

@ 18666私の最初の試みは間違っていた。つまり、式ツリーはSQLに変換可能であり、カスタムファクトリはSQLに変換できません。 **私が間違った部分を捨てた私の更新された答えを見て、私はAutoMapperのアプローチを編集しました**。 –

関連する問題