我不知道为什么,但在我见过的所有教程中都有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
参考?我包含了所有LINQ参考,这对我来说很奇怪。
P.S。 我不确定我做得对,但它仍然很奇怪。
答案 0 :(得分:1)
您可能正在查看较旧的教程......以下内容应该是您需要的(而不是添加)
_db.Tags.InsertOnSubmit( newTag );
_db.SubmitChanges( );
答案 1 :(得分:0)
正如错误消息所示,问题是您使用的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
});