c# - 如何在 LINQ to DB 模型类中添加表之间的关系

我正在使用 LINQ to DB (linq2db),我有一个类 Activity.cs,它有一个 Customer 属性,如下所示:

public Customer Customer { get; set; }

客户类:

    public class Customer
{
    [PrimaryKey, Identity]
    [Column(Name = "CustomerId"), NotNull]
    public string Id { get; set; }

    [Column(Name = "Name")]
    public string Name { get; set; }
}

现在,我希望能够做这样的事情:

db.Activities.First().Customer.Name  //Returns the customer name of an activity

如何设置实体之间的关系,以便我可以像上面解释的那样做?

(是的,我知道将 Id 字段作为字符串没有意义,我必须处理困惑的遗留 Access 数据库)

最佳答案

如果我很好理解,一个Activity 有一个Customer。如果是这样,您应该向您的 Activity 类添加一个关系:

[Table( Name = "Customers" )]
public class Customer
{
    [PrimaryKey, Identity]
    [Column(Name = "CustomerId"), NotNull]
    public string Id { get; set; }

    [Column(Name = "Name")]
    public string Name { get; set; }
}

[Table( Name = "Activities" )]
public class Activity
{
    [PrimaryKey, Identity]
    [Column(Name = "ActivityId"), NotNull]
    public string Id { get; set; }

    [Column( Name = "Customer" )] 
    private int? customerId; 

    private EntityRef<Customer> _customer = new EntityRef<Customer>( );

    [Association(IsForeignKey = true, Storage = "_customer", ThisKey = "customerId" )]
    public Customer Customer{
        get { return _customer.Entity; }
        set { _customer.Entity = value; }
    }
}

A good article about this subject

编辑:

关联不起作用时的绕行:

[Table( Name = "Activities" )]
public class Activity
{
    [PrimaryKey, Identity]
    [Column(Name = "ActivityId"), NotNull]
    public string Id { get; set; }

    [Column( Name = "CustomerId" )] 
    public int? CustomerId; 

}

您可以像这样从事件中检索客户:

var activity = db.Activities.FirstOrDefault()
var customer = db.Customers.FirstOrDefault(c => c.Id = activity.CustomerId);

https://stackoverflow.com/questions/29120917/

相关文章:

ruby-on-rails - rails : validate unique friendship

r - Error in `[<-` (`*tmp*` , , 下标越界 下标越界

clojure - 我如何获得 clojure 中的单元测试列表?

c# - 使用 C# 的条件 JSON 序列化

qt - 如何从 QT 中的 RTSP 流解析 ONVIF 元数据?

can-bus - 使用 ELM327 接收 CAN 报文时的流量控制报文

c# - 使用 Roslyn 时如何验证方法中的参数类型

doctrine-orm - Doctrine2 会选择所有关联的所有字段(来自查询的 JOINS)

netlogo - 如何在 Netlogo 中的海龟之间创建多个链接

html - 高度以像素为单位,而不是百分比