Question

I have a robust set of objects that relate to one another and I need to figure out that best way to handle saving them to the database and still account for things like data constraints.

Let's say I have the following classes:

class Foo
{
    public int Id { get; set; }
    public int BarId { get; set; }
    Bar _bar;
    public Bar Bar 
    {
        get { return _bar; }
        set
        {
            if(_bar != value)
            {
                 _bar = value;
                 BarId = value.Id;
            }
        }
     }
}

class Bar 
{
    public int Id { get; set; }
}

Then let's say I have the following code:

var f = new Foo() { Bar = new Bar() };
SaveFoo(f);

What should I do in SaveFoo to save the objects to the database in the proper order?

IMPORTANT NOTE: I am code generating all of this from my SQL data structure using MyGeneration, and I have access to all Constraints while I'm generating.

Was it helpful?

Solution

You have to work inside out.

If you have a "Navigation property" in your class (in this case, Bar in Foo) it will be accompanied with a foreign id (BarID). So you have to save your nested objects first before saving the object itself.

The problem you risk here are cyclic properties (Author write book, book has Author), in which case you have to properly define which is the primary relationship and which should be ignored.

Then the next problem is cascading deletes.

Was this what you were asking?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top