2018-04-13 10:59

擴充 LinqToSql 的 Left Join 關連 Table

Linq 在處理 Left Join 的語法有點煩人,想採用 EntityRef 的方式進行查詢,而建立 Entity 的關連表的方式很多,但 DBML 都是透過 Visual Studio 的工具去維護的,手動去修改他實在是不優啊!利用 partial class 的方式就可以避開這種問題。

在 AssociationAttribute 中的 IsForeignKey = false 就會採用 Left Join 進行關連查詢。

using System.Data.Linq;
using System.Data.Linq.Mapping;

namespace MyConsoleApp.Database
{
    public partial class JobCommandMaterial
    {
        private Link<Material> _Material;

        [Association(Storage = "_Material", ThisKey = "MaterialCode", OtherKey = "MaterialCode")]
        public Material Material { get { return _Material.Value; } }
    }
}

參考:
AssociationAttribute 類別 (System.Data.Linq.Mapping)
EntityRef(TEntity) 結構 (System.Data.Linq)
Link(T) 結構 (System.Data.Linq)

0 回應: