开发者

LINQ - Add to database does not show up

开发者 https://www.devze.com 2023-03-23 14:50 出处:网络
I don\'t know why but in all tutorials I\'ve seen there is DBObject.TableObject.Add(newObject);. I am not sure why but in my case there is no.

I don't know why but in all tutorials I've seen there is DBObject.TableObject.Add(newObject);. I am not sure why but in my case there is no.

Code

[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

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

Reference? I have all LINQ references included, this is strange to开发者_StackOverflow中文版 me.

P.S. I'm not eve sure if I'm doing it right, but still it is weird.


You are probably looking at older tutorials...the following should be what you need (instead of Add)

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


As the error message says, the problem is that the Add method you're using doesn't accept a parameter of type System.Data.Linq.Table<MvcApplication1.Models.Tag>.

By the looks of it the Add method is expecting a type of Tag. You could do something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消