C# – LINQ: Create persistable Associations in Code, Without Foreign Key

clinqlinq-to-sqlnet

I know that I can create LINQ Associations without a Foreign Key. The problem is, I've been doing this by adding the [Association] attribute in the DBML file (same as through the designer), which will get erased again after I refresh my database (and reload the entire table structure).

I know that there is the MyData.cs file (as part of the DBML) in which I can place my partial extensions etc. to domain objects (to persist even after I refresh the DBML), but I don't know how to create an association there?

Best Answer

You can create a CS file and a custom partial class.

public partial class myClass

And, see if you can place associations there. I haven't worked with custom associations in this way but it looks like it is applied to the property. You can cut and paste the property into the partial class and this will build.

public partial class Parent
{

    [Association(Name = "Parent_Child", Storage = "_Childs", ThisKey = "ParentKey", OtherKey = "ChildKey")]
    public EntitySet<Child> Childs
    {
        get
        {
            return this._Childs;
        }
        set
        {
            this._Childs.Assign(value);
        }
    }
}