2016-12-28 51 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

相关问题