SubmitChanges not “submitting” in LINQ to SQL

2019-09-04 12:41发布

I'm creating an application using WPF, MVVM and LINQ to SQL. I have a collection of notes on an object of type Calculation. I have therefore created a ViewModel-class for this called vmCalculation. My problem is, that when I try to add a note to this object and submit the changes the "note" isn't submittet to the database.

Content of vmCalculation

public class vmCalculation : vmBase
{
    Calculation calc;

    public ObservableCollection<Note> Notes { get; private set; }

    public vmCalculation(Calculation calc)
    {
        this.calc = calc;
        Notes = new ObservableCollection<Note>();
        foreach (var n in calc.Notes) Notes.Add(n);
    }

    public void AddNote()
    {
        Notes.Add(new Note
        {
            NoteText = "New note",
            NoteType = 1
        });
    }

    internal void Save()
    {
        foreach (var n in Notes.Where(n => n.NoteId == 0))
            calc.Notes.Add(n);
    }
}

Method in vmNotes (ViewModel for the "NoteWindow")

public void SaveChanges()
    {
        CurrentCalc.Save();
        DC.SubmitChanges();
    }

CurrentCalc is a property that gets/sets a vmCalculation that I use in the databinding (binding a DataGrid to CurrentCalc.Notes).

When I run AddNote() on CurrentCalc the view is updated just fine with a "New note"-note. But, when I run SaveChanges() the note isn't written to the database.

Any thoughts on this problem?

A possible cause for the the problem could be, that I don't initialize the DataContext (DC) in vmNotes. I get the DataContext from another ViewModel so that I don't destroy the MVVM-structure.

2条回答
闹够了就滚
2楼-- · 2019-09-04 12:43

You must add your new entities to the datacontext before you submit it. Example:

DC.Notes.InsertOnSubmit(NewNote);
DC.SubmitChanges();
查看更多
趁早两清
3楼-- · 2019-09-04 12:44

Thought of a possible solution for my problem.

I updated the SaveChanges()-method on the vmNotes class a bit.

public void SaveChanges()
    {
        var newNotes = currentCalc.Notes.Where(n => n.NoteId == 0);
        DC.Notes.InsertAllOnSubmit(newNotes);
        DC.SubmitChanges();
    }
}

UPDATE 03/09/2011:

Above code is not needed anyway.

I discovered that I had multiple (and static) instances of my DataModel-class.

I cut away some of these and now my original code works just fine!

查看更多
登录 后发表回答