我有两个表,电子邮件和收件人的一个简单的数据模型失败,电子邮件可以被发送到一个或多个收件人MVC LINQ到SQL JOIN定制型的强类型视图
我已经设置了数据库这两个表创建了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);
}
我曾试图通过还使用具有继承=“系统强类型视图中显示为一个单一的记录的输出。 Web.Mvc.ViewPage在aspx页面的顶部,但我得到了以下错误
传递到字典的模型项的类型为“System.Data.Linq.DataQuery`1 [projectMail.Models.AllMailDetail ]'bu该字典需要一个类型为projectMail.Models.AllMailDetail的模型项目。
我固定后,很多搜索这个错误,发现这个职位最有帮助的 MVC LINQ to SQL Table Join Record Display
所以我的观点不再是强类型的,我建立的页面如下
<% foreach (projectMail.Models.AllMailDetail item in (IEnumerable)ViewData.Model)
{ %>
...items...
<% } %>
这工作正常,但似乎漫长。我想不通的事情是
- 为什么第二次查询需要是IQueryable的
- 为什么没有它的工作时,有人强类型
- 怎样才可以做出与工作一个强类型的视图
- 这是处理使用LINQ MVC中的连接到SQL
是的,这工作,对问题的其他部分的任何想法? – best 2009-09-04 06:31:32
只有当您希望在函数返回数据后才能执行更多LINQ时,第二个查询不需要为IQueryable。 你在做连接的方式很好, – TWith2Sugars 2009-09-04 07:27:53