使用 LINQ to SQL 时 类 之间的关系(数据库中没有关系)

Relationship between classes when using LINQ to SQL (no relationship in the DB)

我的数据库中有两个表 -> 活动和客户。每个 Activity 都有一个 CustomerId,但是数据库的设计者没有添加任何外键约束。

我希望能够写作

activity.Customer.Name //Returns name of the customer 

所以我需要一种方法让 LINQ SQL 将 Activity 对象中的 CustomerId 映射到正确的 Customer 对象。

我当然可以:

var customers = db.Customers;
var activities = db.Activities;

然后手动将它们映射到彼此,但这会很痛苦...

这可能吗?不幸的是,添加外键约束不是一种选择。

你可以写下两行。

var customer = db.Customers.First(c => c.Id == activity.CustomerId);
var customerName = customer.Name;

进一步编写扩展方法

static Customer GetCustomer(this Activity)
{
    return db.Customers.First(c => c.Id == activity.CustomerId);
}

并像

一样使用
activity.GetCustomer().Name;