简体   繁体   中英

LINQ-to-SQL Update issue

I am trying to update a list of tags in a Tag table like the following:

List<Tag> tagList = GetUnitTagList(unitId);

        foreach (Tag tag in tagList)
        {
            tag.count = tag.count - 1;
        }

        db.SubmitChanges();

and here is the GetUnitTagList() method:

public static List<Tag> GetUnitTagList(int unitId)
{
    DataClassesDataContext db = new DataClassesDataContext();

    var tags = from x in db.UnitTags where x.UnitID == unitId select x.Tag;

    return tags.ToList();
}

But the value I am trying to update does not get updated.

However, the following code works just fine:

var tags = from x in db.UnitTags where x.UnitID == unitId select x.Tag;

        foreach (Tag tag in tags)
        {
            tag.count = tag.count - 1;
        }

        db.SubmitChanges();

It appears like if I get a collection of Tag objects us a method return then I am not able to update the record. I tried to debug and nothing through an exception!

So, Why is the first way of updating the records is not working while the second way it just work with no problem?

You're updating entities from one dbContext (created in GetUnitTagList ) and calling SubmitChanges on another (created somewhere you don't show us).

In your last example dbcontext is obviously one and same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM