【问题标题】:LINQ - Add to database does not show upLINQ - 添加到数据库不显示
【发布时间】:2011-07-26 16:22:14
【问题描述】:

我不知道为什么,但在我看到的所有教程中都有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 引用,这对我来说很奇怪。

附: 我不确定我是否做得对,但仍然很奇怪。

【问题讨论】:

  • 你在看什么教程?你想使用 _db.Tags.InsertOnSubmit(newTag); _db.CommitChanges()?

标签: c# asp.net linq linq-to-sql asp.net-mvc-3


【解决方案1】:

您可能正在查看较旧的教程...以下应该是您需要的(而不是添加)

_db.Tags.InsertOnSubmit( newTag );
_db.SubmitChanges( );

【讨论】:

  • 谢谢。有效。我以为每个方法只能使用一次 InsertOnSubmit。无论如何,也许您对我的代码有任何提示,我是第一次这样做,不确定它是否足够好。
【解决方案2】:

正如错误消息所述,问题在于您使用的Add 方法不接受System.Data.Linq.Table&lt;MvcApplication1.Models.Tag&gt; 类型的参数。

从外观上看,Add 方法需要 Tag 类型。你可以这样做:

newTag = (from t in _db.Tags
               where t.TagName == tag
                select t).Single()
                           .Select(m => new Tag(){
                             TagName = m.Name
                            });

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多