【发布时间】:2014-01-03 21:33:03
【问题描述】:
我想编写一个 linq 查询来连接一些表并返回一个自定义对象,但是我对多对多表有一些问题,因为我没有任何对象可以使用。您将在最后看到我有问题的 linq 查询,但现在让我向您展示我在 Code First、流畅的 API 和 SQL 方面的优势:
这是我需要使用的所有表(稍后您将看到所有带有 sql 语句的外键):
用户资料
企业简介
出价
招标
UserBusinessProfile 用户和业务资料的多对多表
多对多表是在protected override void OnModelCreating(DbModelBuilder modelBuilder)中定义的这种方式
// Many to many UserProfiles => BusinessProfiles
modelBuilder.Entity<UserProfile>()
.HasKey(primaryKey => primaryKey.Id)
.HasMany(business => business.BusinessProfiles)
.WithMany(user => user.UserProfiles)
.Map(m => m.MapLeftKey("UserProfileId")
.MapRightKey("BusinessProfileId")
.ToTable("UserBusinessProfile"));
就在这里,我需要将 .ToTable("UserBusinessProfile") 包含在我的 linq 查询中...
最后,我的 SQL 语句需要用 linq 编写(SQL 语句按预期工作。):
select * from UserProfile inner join UserBusinessProfile on UserProfile.Id = UserBusinessProfile.UserProfileId inner join BusinessProfile on BusinessProfile.Id = UserBusinessProfile.BusinessProfileId inner join Bid on Bid.UserProfileId = UserProfile.Id and Bid.BusinessProfileId = BusinessProfile.Id inner join Tender on Bid.TenderId = Tender.Id
还有我的 linq 查询:
from UserProfile in context.UserProfile
join UserBusinessProfile in context.UserBusinessProfile on new { Id = UserProfile.Id } equals new { Id = UserBusinessProfile.UserProfileId }
join BusinessProfile in context.BusinessProfile on new { Id = UserBusinessProfile.BusinessProfileId } equals new { Id = BusinessProfile.Id }
join Bid in context.Bid
on new { UserProfileId = UserProfile.Id, BusinessProfileId = BusinessProfile.Id }
equals new { Bid.UserProfileId, Bid.BusinessProfileId }
join Tender in context.Tender on new { TenderId = Bid.TenderId } equals new { TenderId = Tender.Id }
where
UserProfile.Id == 1 &&
BusinessProfile.Id == 1
select new CustomObject{
...
}
如您所见,我无法从我的 linq 查询中使用 context.UserBusinessProfile,因为我没有任何对象可以像其他表一样使用。而且我真的不知道我该如何做到这一点,或者我如何编写我的 linq 查询来完成任务。
感谢您的宝贵时间和帮助,
卡琳
换句话说,当您知道 UserBusinessProfile 是多对多表时,我该如何从这个 SQL 查询中编写 linq 查询??:
select * from UserProfile
inner join UserBusinessProfile on UserProfile.Id = UserBusinessProfile.UserProfileId
inner join BusinessProfile on BusinessProfile.Id = UserBusinessProfile.BusinessProfileId
inner join Bid on Bid.UserProfileId = UserProfile.Id and Bid.BusinessProfileId = BusinessProfile.Id
inner join Tender on Bid.TenderId = Tender.Id
where UserProfile.Id = 1 and BusinessProfile.Id = 1
【问题讨论】:
标签: c# sql linq-to-sql fluent entity-framework-migrations