LINQ -添加到数据库不显示
本文关键字:显示 数据库 添加 LINQ | 更新日期: 2023-09-27 18:03:40
我不知道为什么,但在所有的教程中,我看到有DBObject.TableObject.Add(newObject);
。我不知道为什么,但在我的情况下没有。
[HttpPost]
public ActionResult Index(Post newPost)
{
if (TryUpdateModel(newPost) == true)
{
string[] tagList = { "tag1", "tag2", "tag3"};
_db.Posts.InsertOnSubmit(newPost);
_db.SubmitChanges();
foreach (string tag in tagList)
{
var newTag = new Tag();
if (_db.Tags.Any(x => x.TagName == tag))
{
newTag = (from t in _db.Tags
where t.TagName == tag
select t).Single();
}
else
{
newTag = new Tag()
{
TagName = tag
};
}
// Does not work
_db.Tags.Add(newTag);
var postTag = new PostTag()
{
Tag = newTag,
Post = newPost
};
// Does not work
_db.PostTags.Add(postTag);
}
return Content(Convert.ToString(newPost.ID));
return RedirectToAction("List");
}
else
{
return Content("Fail.");
}
}
错误Error 1 'System.Data.Linq.Table<MvcApplication1.Models.Tag>' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Data.Linq.Table<MvcApplication1.Models.Tag>' could be found (are you missing a using directive or an assembly reference?) C:'Users'Qmal'documents'visual studio 2010'Projects'MvcApplication1'MvcApplication1'Controllers'HomeController.cs 47 30 MvcApplication1
[HttpPost]
public ActionResult Index(Post newPost)
{
if (TryUpdateModel(newPost) == true)
{
string[] tagList = { "tag1", "tag2", "tag3"};
_db.Posts.InsertOnSubmit(newPost);
_db.SubmitChanges();
foreach (string tag in tagList)
{
var newTag = new Tag();
if (_db.Tags.Any(x => x.TagName == tag))
{
newTag = (from t in _db.Tags
where t.TagName == tag
select t).Single();
}
else
{
newTag = new Tag()
{
TagName = tag
};
}
// Does not work
_db.Tags.Add(newTag);
var postTag = new PostTag()
{
Tag = newTag,
Post = newPost
};
// Does not work
_db.PostTags.Add(postTag);
}
return Content(Convert.ToString(newPost.ID));
return RedirectToAction("List");
}
else
{
return Content("Fail.");
}
}
Error 1 'System.Data.Linq.Table<MvcApplication1.Models.Tag>' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Data.Linq.Table<MvcApplication1.Models.Tag>' could be found (are you missing a using directive or an assembly reference?) C:'Users'Qmal'documents'visual studio 2010'Projects'MvcApplication1'MvcApplication1'Controllers'HomeController.cs 47 30 MvcApplication1
参考吗?我有所有的LINQ参考,这对我来说很奇怪。
注:我甚至不确定我这样做是否正确,但它仍然很奇怪。
你可能正在看旧的教程…以下应该是您需要的内容(而不是添加)
_db.Tags.InsertOnSubmit( newTag );
_db.SubmitChanges( );
正如错误消息所说,问题是您正在使用的Add
方法不接受System.Data.Linq.Table<MvcApplication1.Models.Tag>
类型的参数。
从它的外观来看,Add方法期望Tag
类型。你可以这样做:
newTag = (from t in _db.Tags
where t.TagName == tag
select t).Single()
.Select(m => new Tag(){
TagName = m.Name
});