我想为新闻创建类别。这将是多对多的关系。怎么做得好?我创建了两个类:
public class News
{
public News()
{
this.NewsCategories = new List<NewsCategory>();
}
public int ID { get; set; }
public DateTime Date { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public IEnumerable<NewsCategory> NewsCategories { get; set; }
}
public class NewsCategory
{
public NewsCategory()
{
this.News = new List<News>();
}
public int ID { get; set; }
public string Name { get; set; }
public IEnumerable<News> News { get; set; }
}
但EF只创建两个表...没有连接表。我也创建了自定义DbInitializer:
public class TouristGuideDBInitializer : DropCreateDatabaseAlways<TouristGuideDB>
{
protected override void Seed(TouristGuideDB context)
{
base.Seed(context);
context.NewsCategories.Add(new NewsCategory { Name = "Default" });
context.NewsCategories.Add(new NewsCategory { Name = "Second" });
context.News.Add(new News { Date = DateTime.Now, Text = "asasdfas fasdfa sdf asf asf", Title = "Hello world" });
context.SaveChanges();
var news = context.News.First();
var cat = context.NewsCategories.Where(r => r.Name == "Default").Single();
news.NewsCategories.ToList().Add(cat);
context.SaveChanges();
}
}
但它只添加一个新闻和两个类别......没有关系...... 如何正确地完成(关系)?
答案 0 :(得分:1)
您需要使用ICollection<T>
作为导航属性。