gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:16:07 25 4
gpt4 key购买 nike

我正在使用 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);

关于c# - 如何在 LINQ to DB 模型类中添加表之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29120917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com