【问题标题】:Relationship between classes when using LINQ to SQL (no relationship in the DB)使用 LINQ to SQL 时类之间的关系(数据库中没有关系)
【发布时间】:2015-03-29 08:29:48
【问题描述】:

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

我希望能够写作

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

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

我当然可以:

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

然后手动将它们相互映射,但这会很痛苦......

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

【问题讨论】:

  • 我认为您可能会修改 edmx 中的关系,但每次更新模型时这些可能会被覆盖。没测试过。
  • 使用 AssociationAttribute 怎么样?不确定这是否要求数据库中存在约束。看看这个:msdn.microsoft.com/en-us/library/…

标签: c# linq-to-sql


【解决方案1】:

你可以写下两行。

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多