2016-12-28 50 views
1

我有這些模型更新許多到許多實體框架的關係拋出一個lambda表達式錯誤

public class Admin 
{ 
    public Admin() 
    { 
     this.course = new HashSet<Courses>(); 
    } 

    [Key] 
    public int ID { get; set; } 
    public string LoginName { get; set; } 

    public virtual ICollection<Courses> course { get; set; } 
} 

public class Courses 
{ 
    public Courses() 
    { 
     this.admin = new HashSet<Admin>(); 
    } 

    [Key] 
    public int ID { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<Admin> admin { get; set; } 
} 

,這是我的控制器方法來更新

public ActionResult Admins(Admin rec, IList<int> CourseId) 
{  
    if (rec.ID > 0) // edit 
    { 
     var dbrec = db.Admins.Include("Courses").Where(s => s.ID == rec.ID).FirstOrDefault<Admin>(); 
     dbrec.DisplayName = rec.DisplayName; 

     var deletedCourses = dbrec.course.Except(rec.course, cours => cours.ID).ToList<Courses>(); 
    } 
} 

我在這裏面對的問題這行代碼cours => cours.ID

錯誤消息

不能轉換lambda表達式類型的IEqualityComparer,因爲它不是一個委託類型

誰能告訴我,爲什麼我得到這個錯誤?

我下面這個教程

http://www.entityframeworktutorial.net/EntityFramework4.3/update-many-to-many-entity-using-dbcontext.aspx

+0

你錯用了'Except()'。 'var deletedCourses = dbrec.course.Except(rec.course).ToList ();'this get all _except_'rec' –

回答

1

基本上Except()樣子:

public static IEnumerable<TSource> Except<TSource>(
this IEnumerable<TSource> first, 
IEnumerable<TSource> second) 

所以,你可以用它

var deletedCourses = dbrec.course.Except(rec.course).ToList<Courses>(); 這讓所有course除了rec

爲什麼你會收到錯誤?簡單,你需要使用上面的代碼,而不是你或使用擴展 爲Except()方法

public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other,                   Func<T, TKey> getKey) 
{ 
    return from item in items 
      join otherItem in other on getKey(item) 
      equals getKey(otherItem) into tempItems 
      from temp in tempItems.DefaultIfEmpty() 
      where ReferenceEquals(null, temp) || temp.Equals(default(T)) 
      select item; 

} 

我們使用以下的擴展方法值從兩個列表比較,並從其中不存在到第二列表中的一個列表返回實體。根據傳遞函數發生比較:

+0

謝謝,現在我明白了爲什麼我得到這個錯誤 – Sarah

相關問題