我有两个表的简单数据模型,电子邮件和收件人,电子邮件可以发送给一个或多个收件人
我已经用这两个表设置了数据库,创建了 Linq to SQL 存储库,构建了控制器和强类型视图。
当我想从数据库中选择所有记录时,这很好用
public IList<AllMailDetail> ListAll()
{
var allMail =
from m in _datacontext.mail_receiveds
join r in _datacontext.mail_recipients on m.DeliveryId equals r.DeliveryId
select new AllMailDetail {
DeliveryId = m.DeliveryId,
MessageId = m.MessageId,
SentFrom = m.SentFrom,
FilePath = m.FilePath,
FileName = m.FileName,
SentDateTime = m.SentDateTime,
ReceivedDateTime = m.ReceivedDateTime,
Subject = m.Subject,
SpamScore = m.SpamScore,
IsSpam = m.IsSpam,
SenderIP = m.SenderIP,
Header = m.Header,
SentTo = r.SentTo
};
return allMail.ToList <AllMailDetail>();
}
自定义类型类
public class AllMailDetail
{
public int DeliveryId { get; set; }
public int? MessageId { get; set; }
public string SentFrom { get; set; }
public string FilePath { get; set; }
public string FileName { get; set; }
public string SentDateTime { get; set; }
public DateTime ReceivedDateTime { get; set; }
public string Subject { get; set; }
public byte? SpamScore { get; set; }
public bool? IsSpam { get; set; }
public string SenderIP { get; set; }
public string Header { get; set; }
public string SentTo { get; set; }
}
控制器只是将内容从存储库发送到强类型视图
public ActionResult Index()
{
return View(_repository.ListAll());
}
要从数据库中只获取一条邮件记录,我有以下代码,它接受一个 deliveryId
public IQueryable<AllMailDetail> GetMail(int? id)
{
var allMail =
from m in _datacontext.mail_receiveds
join r in _datacontext.mail_recipients
on m.DeliveryId equals r.DeliveryId
where m.DeliveryId == id
select new AllMailDetail
{
DeliveryId = m.DeliveryId,
MessageId = m.MessageId,
SentFrom = m.SentFrom,
FilePath = m.FilePath,
FileName = m.FileName,
SentDateTime = m.SentDateTime,
ReceivedDateTime = m.ReceivedDateTime,
Subject = m.Subject,
SpamScore = m.SpamScore,
IsSpam = m.IsSpam,
SenderIP = m.SenderIP,
Header = m.Header,
SentTo = r.SentTo
};
return allMail;
}
及其控制器代码
public ActionResult Details(int? id)
{
var mail = _repository.GetMail(id);
if (mail == null)
return View("NotFound");
return View(mail);
}
我一直在尝试通过使用在 aspx 页面顶部具有 Inherits="System.Web.Mvc.ViewPage 的强类型视图来显示单个记录的输出,但出现以下错误
传入字典的模型项的类型为“System.Data.Linq.DataQuery`1[projectMail.Models.AllMailDetail]”,但此字典需要类型为 projectMail.Models.AllMailDetail 的模型项。
经过大量搜索后,我修复了这个错误,发现这篇文章最有帮助 MVC LINQ to SQL Table Join Record Display
所以我的视图不再是强类型的,我构建页面如下
<% foreach (projectMail.Models.AllMailDetail item in (IEnumerable)ViewData.Model)
{ %>
...items...
<% } %>
这很好用,但似乎还有很长的路要走。我想不通的是
- 为什么第二个查询需要是 IQueryable
- 为什么当视图是强类型时它不起作用
- 如何使它与强类型视图一起工作
- 这是使用 LINQ to SQL 在 MVC 中处理连接的最佳方式吗