I am pretty new to working with XAML and LINQ and could really do with some help. I need to be able to create and then save new records to my database (bound to objects on my XAML view). I can currently load and existing record, make the changes and then save (see test example below), but not from scratch (and I've spent far too much time today trying to figure it out).

In short, I need to start off with an empty record, and then save it (basic stuff I'm guessing).

        egwEntities db = new egwEntities();
        private egw_addressbook mvm = new egw_addressbook();

        private void GetData()
            DataContext = mvm;
            var result = (from o in db.egw_addressbook where o.contact_id == 16875 select o).FirstOrDefault();
            if (result == null) return;
            mvm.org_name = result.org_name;
            mvm.hex_srv_start = result.hex_srv_start;

        private void btnSave_Click(object sender, RoutedEventArgs e)
            var abook = db.egw_addressbook.Local.FirstOrDefault(o => o.contact_id == 16875);
            abook.org_name = mvm.org_name;
            abook.hex_srv_start = mvm.hex_srv_start;
2 Years
Discussion Span
Last Post by Ketsuekiame

Well it should all work the same way, how are you initiating the "Create New" logical task? It should be as simple as adding the data object to your context and saving, but you will need code logic to handle that case rather than updating existing model data.


Thanks again Ketsuekiame - but this is what I'm struggling with. I'm really new to working this way, and everything seems to be taking far longer than it should.

Based on my code above - could you point me in the right direction (it would be greatly appreciated)?


It depends how you've implemented you view, which I can't see from the code there.

If you're using a datagrid then if you make the control editable, adding new lines should be automatic. If you're using custom binding, you will need to add a "Create New..." button or similar. That way you will add a new, empty object to your control and set the bindings to it. When you click Save, as the object has been inserted into your datacontext, it should automatically create it in the database.

You may have to call the Insert method on your datacontext. If so, find some way of knowing that you're adding a new record and call "Insert"/"Add".

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.