AddAssociation

,

AddAssociation allows you to add a one-to-many association between two entities. This method results in a foreign key constraint being added to the column that holds the primary key of the foreign table.

AddAssociation accepts a single parameter, associationPropertyName, which is the name of the entity member that holds the foreign key of another table.

To illustrate, if we were to add a new association between the TwitterUser and the TimelineItem classes that matches the existing association, we would first set about by adding a new property to the TimelineItem class to hold the id of a TwitterUser, like so:

[Table]
public class TimelineItem : NotifyPropertyChangeBase
{
    string twitterUser2Id;

    [Column]
    public string TwitterUser2Id
    {
        get
        {
            return twitterUser2Id;
        }
        set
        {
            Assign(ref twitterUser2Id, value);
        }
    }

    EntityRef<TwitterUser> user2;

    [Association(Storage = "user2", ThisKey = "TwitterUser2Id",
                 IsForeignKey = true, Name = "FK_TwitterUser2")]
    public TwitterUser TwitterUser2
    {
        get
        {
            return user2.Entity;
        }
        set
        {
            user2.Entity = value;
        }
    }
...
}


Tip

Explicitly providing a name for the foreign key constraint avoids collisions with existing constraint names, especially if similar associations have already been defined, as is the case with our TwitterUser property.


On the other side, the one side of the association, we would create a new EntitySet property for the new TimelineItem children, as shown:

[Table]
[Index(Columns = "ScreenName")]
public class TwitterUser : NotifyPropertyChangeBase
{
    readonly EntitySet<TimelineItem> timelineItems2;

    [Association(
        Storage = "timelineItems2",
        OtherKey = "TwitterUserId")]
    public EntitySet<TimelineItem> TimelineItems2
    {
        get
        {
            return timelineItems2;
        }
        set
        {
            timelineItems2.Assign(value);
        }
    }
...
}

To materialize the association in the database, we would then perform the following updates:

using (TwitterDataContext dataContext
                   = twitterDatabaseUtility.CreateContext())
{
    DatabaseSchemaUpdater updater
                   = dataContext.CreateDatabaseSchemaUpdater();
    updater.AddColumn<TimelineItem>("TwitterUser2Id");
    updater.AddAssociation<TimelineItem>("TwitterUser2");
    updater.Execute();
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.118.210