[英]Convert simple t-sql query to linq
我正在努力查詢。 我知道如何用SQL編寫它,但是在查看了許多示例並使用Linqer之后,將其轉換為linq並沒有取得任何成功。 有人可以指出我正確的方向...
SELECT contacts.firstname, contacts.lastname
FROM businesscontacts INNER JOIN
contacts ON businesscontacts.contactsid = contacts.contactsid INNER JOIN
contactscontactcodes ON contacts.contactsid = contactscontactcodes.contactsid
我認為這非常接近,但是聯系方式當然沒有定義...
string sendto = from businesscontacts in db.businesscontacts
from t in contacts.contactcodes
select new {
businesscontacts.contacts.firstname,
businesscontacts.contacts.lastname
};
如果我在數據庫上下文之前...
string sendto = from businesscontacts in db.businesscontacts
from t in db.contacts.contactcodes
select new {
businesscontacts.contacts.firstname,
businesscontacts.contacts.lastname
};
則聯系代碼不可用
您需要使用Linq join
關鍵字來連接表,就像在sql中一樣。
這是一個很好的資源,可助您與Line接軌。 101個LINQ樣本
var results = from bc in db.businesscontacts
join c in db.contacts
on bc.contactsid equals c.contactsid
join cc in db.contacts.contactcodes
on c.contactsid = cc.contactsid
select new { FirstName = c.FirstName, LastName = c.LastName;
嘗試:
var names = from bContacts in db.businesscontacts
join contacts in db.contacts on bContacts.contactsid equals ontacts.contactsid
join cCodes in db.contacts.contactcodes on contacts.contactsid equals cCodes.contactsid
select new
{
FirstName = contacts.firstname,
LastName = contacts.lastname
};
如果您在數據庫上設置了外鍵約束,則完全不需要進行任何聯接。 請注意,我更改了sendto
的聲明,因為在這里string
沒有意義。
var sendto = from businesscontact in db.businesscontacts.Include(bc => bc.contact)
select new {
businesscontact.contact.firstname,
businesscontact.contact.lastname
};
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var businesscontacts = new List<businesscontacts>();
var contacts = new List<contacts>();
var contactcodes = new List<contactcodes>();
var sendto = from bc in businesscontacts
from c in contacts
from cc in contactcodes
where bc.Contactid == c.Contactid && cc.Contactid == c.Contactid
select new
{
c.FirstName,
c.LastName
};
}
}
class businesscontacts
{
public int Contactid { get; set; }
}
class contacts
{
public int Contactid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class contactcodes
{
public int Contactid { get; set; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.