简体   繁体   English

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

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

I have two tables in my database -> Activities and Customers. 我的数据库中有两个表->活动和客户。 Each Activity has a CustomerId, however the designers of the database haven't added any foreign key constraints. 每个活动都有一个CustomerId,但是数据库的设计人员没有添加任何外键约束。

I want to be able to write 我想写

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

So I need a way of telling LINQ to SQL to map the CustomerId in the Activity object to the correct Customer object. 因此,我需要一种告诉LINQ到SQL的方法,以将Activity对象中的CustomerId映射到正确的Customer对象。

I could of course do : 我当然可以做:

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

And then manually map them to each other, but that would be a pain... 然后手动将它们相互映射,但这会很痛苦...

Is this is possible? 这可能吗? Adding foreign key constraints is unfortunately not an option. 不幸的是,添加外键约束不是一种选择。

You can write next two lines. 您可以写下两行。

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

One step further write an extension method 一步进一步编写一种扩展方法

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

and use like 并使用像

activity.GetCustomer().Name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM