简体   繁体   English

具有Linq.Dynamic的C#实体框架:按COALESCE排序

[英]C# Entity Framework with Linq.Dynamic: ORDER BY COALESCE

I got two tables, dbo.Foo and dbo.Bar . 我有两个表dbo.Foodbo.Bar

dbo.Foo got two important properties: dbo.Foo两个重要属性:

  • ID (Primary key) ID (主键)
  • OwnerID (Foreign key to the same table (ID)) OwnerID (同一表的外键(ID))

dbo.Bar got three important properties: dbo.Bar三个重要属性:

  • ID (Primary key) ID (主键)
  • FooID (Foreign key to dbo.Foo (ID)) FooIDdbo.Foo (ID)的外键)
  • FooOwnerID (Foreign key to dbo.Foo (ID) too) FooOwnerIDFooOwnerID外键dbo.Foo (ID)也是)

In dbo.Bar , FooID OR FooOwnerID has to be set. dbo.Bar ,必须设置FooIDFooOwnerID Below I created a graphic to show the structure: 下面,我创建了一个图形来显示结构:

数据模型

My model class for dbo.Bar looks like: 我的dbo.Bar模型类如下:

public class Bar
{
    public int ID { get; set; }
    public int FooID { get; set; }
    public int FooOwnerID { get; set; }

    public virtual Foo Foo { get; set; }
    public virtual Foo FooOwner { get; set; }
}

The mapping for the table (using the fluent-api) looks like: 该表的映射(使用fluent-api)如下所示:

modelBuilder.Entity<Bar>().ToTable("Bar", "dbo");
modelBuilder.Entity<Bar>().HasKey(x => x.ID);
modelBuilder.Entity<Bar>().Property(x => x.FooID).IsRequired();
modelBuilder.Entity<Bar>().Property(x => x.FooOwnerID).IsRequired();
modelBuilder.Entity<Bar>().HasOptional(x => x.Foo).WithMany().HasForeignKey(x => x.FooID);
modelBuilder.Entity<Bar>().HasOptional(x => x.FooOwner).WithMany().HasForeignKey(x => x.FooOwnerID);

This works. 这可行。 But I want to have FooOwner to be the actual owner of Foo instead of null if only FooID is set. 但是我想让FooOwner成为Foo的实际所有者,而不是如果只设置了FooID则为null Does someone have a idea how to do this? 有人知道如何执行此操作吗?

Background 背景

I am using DataTables to display the data at the view. 我正在使用DataTables在视图中显示数据。 To order the items, DataTables sends the name of the column to order ( Foo.ID for example). 要订购商品,DataTables Foo.ID顺序发送列名(例如Foo.ID )。 I am using Linq.Dynamic to order the result set dynamically. 我正在使用Linq.Dynamic动态排序结果集。 An order string look like this: Foo.ID asc, PropertyOfBar desc . 订单字符串如下所示: Foo.ID asc, PropertyOfBar desc

Does someone have a idea how to do this? 有人知道如何执行此操作吗?

Nothing built-in. 没有内置的。 But you can always use a method or a NotMapped property 但是您始终可以使用方法或NotMapped属性

eg 例如

public Foo GetFooOwner() => FooOwner??Foo.Owner;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM