Renaming LINQ 2 SQL Entity Properties Through Partial Classes

依然范特西╮ 提交于 2019-12-11 04:37:34

问题


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?


回答1:


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();
        }



回答2:


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.



来源:https://stackoverflow.com/questions/741898/renaming-linq-2-sql-entity-properties-through-partial-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!