我有三张桌子
当我创建新的News
项目时,我需要为该新项目分配类别。
我的代码看起来像那样
var NewsToSave = new News();
NewsToSave.NewsBody = model.NewsBody;
NewsToSave.NewsTitle = model.NewsTitle;
NewsToSave.NewsImagePath = NewsImagePath;
NewsToSave.NewsDate = System.DateTime.Now;
db.News.Add(NewsToSave);
db.SaveChanges();
foreach (var id in SelectedIDs)
{
// How to assign selected categories to NewsToSave object and save the Ids in the middle table
}
如何将选定的类别分配给NewsToSave
对象?
谢谢
答案 0 :(得分:0)
您可以这样覆盖您的上下文:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<NewsToSave>()
.HasMany(c => c.Categories).WithMany(i => i.NewsToSaves)
.Map(t => t.MapLeftKey("NewsToSaveID")
.MapRightKey("CategoryID")
.ToTable("NewsCategory"));
}
处理添加的数据:
void AddOrUpdateNews(Context context, int categoryId, string newsTitle)
{
var cat = context.Categories.SingleOrDefault(c => c.Id == categoryId);
var nws = cat.News.SingleOrDefault(n => n.Title == newsTitle);
if(nws == null)
{
cat.News.Add(context.News.SingleOrDefault(c => c.Title == newsTitle));
}
}
这对我几个月前制作的ASP.NET应用程序非常有用。希望它可以帮助你。
答案 1 :(得分:0)
您可以为每个ID创建一个类别,附加它(假设它已经存在于数据库中),然后将其添加到新闻的Categories
列表并保存:
foreach(var id in SelectedIDs)
{
var category = new Category { CategoryId == id};
db.Categories.Attach(category);
NewsToSave.Add(category);
}
db.News.Add(NewsToSave);
db.SaveChanges();
答案 2 :(得分:0)
foreach (var id in SelectedIDs)
{
// You have to load the category from Db
var cat = db.Categories.FirstOrDefault(x=> c.Id == id);
// Added to the NewsToSave
if (cat !=null)
NewsToSave.Categories.Add(cat);
}
// Store the changes
db.SaveChanges();