Question

Can I use partial classes to create properties that points to an association property generated by the L2S designer. Also, will I be able to use the new property in queries?

How can I achieve this?

Was it helpful?

Solution

Yes you can, but you have to apply the same attributes as the linq2sql generated property i.e.

    [Association(Name="Test_TestData", Storage="_TestDatas", ThisKey="SomeId", OtherKey="OtherId")]
    public System.Data.Linq.EntitySet<TestData> MyTestDatas
    {
        get
        {
            return this.TestDatas;
        }
    }

TestDatas being the original relation.

Update: A sample query I ran:

        var context = new DataClasses1DataContext();
        var tests =
            from d in context.Tests
            where d.MyTestDatas.Any(md=>md.MyId == 2)
            select new
            {
                SomeId = d.SomeId,
                SomeData = d.SomeData,
                Tests = d.MyTestDatas
            };
        foreach (var test in tests)
        {
            var data = test.Tests.ToList();
        }

OTHER TIPS

If you just want to give a different name to the association property, just use the Property page for the association and rename the parent and/or child property. That will change the name of the EntityRef/EntitySet in the class.

EDIT: The downside of using a separate property in a partial class is that LINQ won't be able to use it when generating queries -- essentially you'll be forced to always get the entities before you can use the related properties on the object. By renaming you allow LINQ to use the related properties in constructing the query which can result in a more efficient query. For example, if you want to get entities where a related entity has a particular property value, using the attribute decorated entity will allow LINQ to generate the SQL to pull just those matching values from the database. With the naive property implementation (that simply references the underlying relation property, in effect renaming it), you will be forced to first get all entities, then do the filtering in your application.

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