C# 使用JOIN将SQL转换为LINQ
我正在尝试学习ASP.NET MVC,我对ASP.NET Webforms有一些了解,但我将来要合作的公司希望我学习MVC,所以我正在尝试将我的一个旧Webforms项目“迁移”到MVC。只是为了了解模式和差异 我先做数据库,因为我以前已经有了数据库,让Visual Studio使用模型类和DB“上下文文件”将其转换为ADO.NET数据模型 我的问题是,我正试图通过几个“模型”与LINQ一起查看。我的数据库如下所示:C# 使用JOIN将SQL转换为LINQ,c#,sql,asp.net-mvc,linq,join,C#,Sql,Asp.net Mvc,Linq,Join,我正在尝试学习ASP.NET MVC,我对ASP.NET Webforms有一些了解,但我将来要合作的公司希望我学习MVC,所以我正在尝试将我的一个旧Webforms项目“迁移”到MVC。只是为了了解模式和差异 我先做数据库,因为我以前已经有了数据库,让Visual Studio使用模型类和DB“上下文文件”将其转换为ADO.NET数据模型 我的问题是,我正试图通过几个“模型”与LINQ一起查看。我的数据库如下所示: (来源:) 我以前使用的SQL语法如下所示: SELECT TOP 6
(来源:) 我以前使用的SQL语法如下所示:
SELECT
TOP 6
Performance.PerformanceId,
Performance.ActId,
Performance.[Date],
Act.Title,
Act.[Description],
Act.Imageurl,
Stage.Stagename,
Artistname.Artistname
FROM
Performance
JOIN Act ON Performance.ActId=Act.ActId
JOIN STAGE ON Performance.Stage=Stage.StageId
JOIN [User] ON Act.ArtistId=[User].UserId
JOIN Artistname ON [USER].UserId=Artistname.ArtistId
WHERE Performance.[Date] > GETDATE()
ORDER BY YEAR(Performance.[Date])
我只是不知道如何将其传递给视图,我可以传递PerformanceID、ActID和Date,因为它们都是Performance的属性,但是如何添加其余的属性呢
这是我的控制器:
public ActionResult Index()
{
var q = (from Performance in db.Performance
join Stage in db.Stage on new { Stage = (int)Performance.Stage } equals new { Stage = Stage.StageId }
join Artistname in db.Artistname on new { UserId = Performance.Act.User.UserId } equals new { UserId = Artistname.ArtistId }
where
Performance.Date > SqlFunctions.GetDate()
orderby
SqlFunctions.DatePart("year", Performance.Date)
select new
{
Performance.PerformanceId,
Performance.ActId,
Performance.Date,
Performance.Act.Title,
Performance.Act.Description,
Performance.Act.Imageurl,
Stage.Stagename,
Artistname.Artistname1
}).Take(6).ToList();
var performance = new List<Performance>();
foreach (var per in q)
{
performance.Add(new Performance()
{
PerformanceId = per.PerformanceId,
ActId = per.ActId,
Date = per.Date
// TODO : add Title, Description, Imageurl, stagename, artistname
});
}
return View(performance);
}
public ActionResult Index()
{
var q=(来自性能,单位为db.Performance
在db.Stage中加入Stage on new{Stage=(int)Performance.Stage}等于new{Stage=Stage.StageId}
在db.Artistname中加入Artistname,新的{UserId=Performance.Act.User.UserId}等于新的{UserId=Artistname.ArtistId}
哪里
Performance.Date>SqlFunctions.GetDate()
排序子句
SqlFunctions.DatePart(“年”,Performance.Date)
选择新的
{
Performance.PerformanceId,
Performance.ActId,
演出日期,
表演、表演、头衔,
行为描述,
Performance.Act.Imageurl,
舞台,舞台剧,
Artistname.Artistname1
}).采取(6)措施;
var performance=新列表();
foreach(每平方英寸的var)
{
添加(新性能()
{
PerformanceId=按per.PerformanceId,
ActId=每ActId,
日期=每个日期
//TODO:添加标题、说明、图像URL、舞台名称、艺人名称
});
}
返回视图(性能);
}
谢谢你的关心,如果你需要更多的信息,请告诉我 为此,我认为您需要创建一个不同的模型,该模型具有您必须发送到视图的所有必需属性。不要使用实体,而是尝试创建具有所需所有属性的ViewModel,并将其命名为PerformanceViewModel。您也可以直接使用
选择新的PerformanceViewModel
,而不是再次循环到结果集中。非常感谢您,先生!成功了!:)所以你会建议每次你必须连接2+个不同类别的表时都制作ViewModels?是的,先生,这是唯一的出路。对于直接表,您可以直接使用实体,但我不认为您应该在Web层中公开您的数据库实体。我真的很高兴您能帮助我并给我一些额外的技巧!顺便问一下,你说的“但我不认为你应该在Web层公开你的数据库实体”是什么意思?你会更好地了解这一点