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