如何使用IEnumerable模拟List<> [英] How do I use the IEnumerable to emulate a List<>
本文介绍了如何使用IEnumerable模拟List<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这种情况下,我对IEnumerable有点困惑。它是否准确描述了List< Class1>?
错误在foreach语句中只有foreach是红色下划线而不是item或者模型。
错误代码:
I am a little confused about the IEnumerable in this case. Does it accurately depict List<Class1>?
The error is in the "foreach" statement only the "foreach" is red underlined but not the "item" or the "Model".
Error Code:
foreach statement cannot operate on variables of type 'System.Collections.Generic.IEnumerator<SimpleMVC5.Models.Class1>' because 'System.Collections.Generic.IEnumerator<SimpleMVC5.Models.Class1>' does not contain a public definition for 'GetEnumerator' c:\Users\Optiplex760\Documents\a ASP.net 4.5\csharp\a MVC\SimpleMVC5\SimpleMVC5\Views\Home\Index.cshtml
Index.cshtml
Index.cshtml
@model IEnumerable<SimpleMVC5.Models.Class1>
<table>
@foreach (var item in Model)
{
<tr>
<td>@item.idt</td>
<td>@item.datetime0</td>
<td>@item.col1</td>
<td>@item.col2</td>
<td>@item.col3</td>
</tr>
}
</table>
HomeController.cs
HomeController.cs
public class HomeController : Controller
{
private testContext db = new testContext();
List<Class1> lst = new List<Class1>();
public ActionResult Index()
{
lst = db.Data1.ToList();
return View(lst);
}
Class1.cs
Class1.cs
public class Class1
{
public int idt { get; set; }
public string datetime0 { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
public class testContext : DbContext
{
public DbSet<Class1> Data1 { get; set; }
}
web.config
web.config
<connectionStrings>
<add name="testContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\SimpleMVC5db.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
和SimpleMVC5db.mdf已定义并填充数据。
如果我在lst = db.Data1.ToList();行调试它。错误代码:
And SimpleMVC5db.mdf is defined and is populated with data.
If I debug it on line "lst = db.Data1.ToList();". Error code:
An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: One or more validation errors were detected during model generation:
推荐答案
Class1
没有定义键。密钥按惯例,属性或流畅的api标识:创建使用实体框架代码的主键首先 [ ^ ]
尝试:
Class1
has no key defined. Keys are either identified by convention, by attribute or fluent api: Create Primary Key using Entity Framework Code First[^]
Try:
public class Class1
{
[Key]
public int idt { get; set; }
public string datetime0 { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
这篇关于如何使用IEnumerable模拟List<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文