Handling Contraints And Identifiers In A Custom Object Model For Persisting To A Relational Database

StackOverflow https://stackoverflow.com/questions/7493297

문제

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.

도움이 되었습니까?

해결책

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top