使用entityframework修改收集

时间:2015-12-03 07:43:43

标签: c# entity-framework

在我的项目中,我有一个实体类

public partial class Movie
{
public Movie()
{
this.MovieCategories = new HashSet<MovieCategory>();
}

public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<MovieCategory> MovieCategories { get; set; }
}

public partial class MovieCategory
{
public int Id { get; set; }
public int CategoryId { get; set; }
public int MovieId { get; set; }
public virtual Category Category { get; set; }
public virtual Movie Movie{ get; set; }
}


public partial class Category
{
public Category()
{
    this.MovieCategories = new HashSet<MovieCategory>();
}
public int Id { get; set; }
public string Category1 { get; set; }
public virtual ICollection<MovieCategory> MovieCategories { get; set; }

}

我查看了我可以在哪里添加或删除&#34; MovieCategories&#34;使用列表框。

Bellow是我尝试使用entityframework更新我的电影对象的方式。

    _movieReviewEntities.Movies.Attach(movie);
    _movieReviewEntities.Entry(movie).State = EntityState.Modified;
    _movieReviewEntities.SaveChanges();

这是更新&#34; Id&#34;,&#34;名称&#34; &安培; &#34;说明&#34;属性但没有更新我的收集&#34; MovieCategories&#34;

如何更新&#34; MovieCategories&#34;还??

2 个答案:

答案 0 :(得分:1)

例如,您有一个新的MovieCategory,并且想要使用这个新的MovieCategory更新电影。

请注意我没有测试过。

MovieCategory newCategory = new MovieCategory
{
   "Action Movie"
};

movie.MovieCategories.Add(newCategory);

_movieReviewEntities.Movies.Attach(movie);
_movieReviewEntities.Entry(movie).State = EntityState.Modified;
_movieReviewEntities.SaveChanges();

这也应该添加新的电影类别。

如果您的表格中存在您的类别

var existingCategory = _movieReviewEntities.MovieCategories.Where(m => m.Name == "Action Movie")
.Select(m => m).FirstOrDefault();

if(existingCategory != null)
{
   movie.MovieCategories.Add(existingCategory);
}

如果您有一个包含所选电影类别的ListBox示例。

//From ListBox
var fromSelection = new List<string>("Comedy", "Drama");

//Fetch from table
var categoryListToAdd = movie.MovieCategories.Where(x => fromSelection.Contains(x.Name)).Select(x => x).ToList();

if(categoryListToAdd.Count > 0)
{
    //Existing categories of the movie.
    var categoryList = movie.MovieCategories.Select(x => x).ToList();


    //Remove the related records.
    if(categoryList.Count > 0)
       categoryList.ForEach(x => _movieReviewEntities.MovieCategories.Remove(x));

    //Then add the selected categories. 
    categoryListToAdd.ForEach(x => _movieReviewEntities.Add(x));
}

同样,这没有经过测试。希望你明白这一点。

答案 1 :(得分:0)

要修改EF上下文中的关系,应通过上下文跟踪两个相关对象。这意味着您必须将MovieMovieCategory对象附加到上下文以修改它们之间的关系。

顺便说一句,如果您加载实体,它们会保持附加在上下文中。这是一个简单的例子,您可以如何使用它的类别加载电影并清除所有类别并添加一个新类别:

using (var context = new MovieContext())
{
    var movie = context.Movies.Include(m => m.MovieCategories).First(m => m.Name == "Green Elephant");
    movie.MovieCategories.Clear();
    var newCategory = context.MovieCategories.Create();
    newCategory.Name = "Trash";
    movie.MovieCategories.Add(newCategory);
    context.SaveChanges();
}