我发布更多内容是因为我想了解更多信息,因为我的解决方法是基本上避免使用 LINQ to Entities!如果我能使用它就好了。所以如果有人可以启发我..
我正在开发一个 ASP.Net MVC 3 应用程序(我的第一个应用程序),使用代码优先的实体框架作为我的数据模型。这将是一个在线商店,我正在开发“管理”控制器,作为管理员,您将能够编辑产品等。在添加新产品时,您必须指定一个类别,这意味着类别的下拉列表。
我首先根据我找到的信息在 ViewBag 中返回 IEnumerable 类别集合here http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists。这似乎是一种非常好的处理事情的方式。
但我遇到了同样的错误,您将在下面看到。因此,根据我在网上阅读的建议,我创建了一个单独的模型,专门用于创建新产品和编辑现有产品。类别集合用于在视图中构建下拉列表。
public class ProductModel
{
public int Id { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public bool IsVisible { get; set; }
public IEnumerable<SelectListItem> Categories
{
get
{
return new DataAccess()
.Categories
.OrderBy(c => c.Description)
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Description
});
}
}
}
这会导致以下错误消息:“LINQ to Entities 无法识别“System.String ToString()”方法,并且该方法无法转换为存储表达式。”。一种建议的在线解决方案是使用实体框架提供的 SqlFunction 方法。所以我尝试了这个......
public IEnumerable<SelectListItem> Categories
{
get
{
return new DataAccess()
.Categories
.OrderBy(c => c.Description)
.Select(c => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)c.Id),
Text = c.Description
});
}
}
但这会导致以下错误消息:“类型“System.Data.Objects.SqlClient.SqlFunctions”上指定的方法“System.String StringConvert(System.Nullable`1[System.Double])”无法转换为 LINQ to Entities 存储表达式。".
我什至尝试向名为的数据类添加一个只读属性字符串形式的 ID,但这显然让实体框架非常不高兴!
最后,我意识到我投入的所有时间都是不值得的,因此完全停止使用 LINQ。这工作得很好,但很高兴知道是否有一种“正确”的方法来做到这一点,真正有效!
这是我当前的工作解决方案:
public IEnumerable<SelectListItem> Categories
{
get
{
var dal = new DataAccess();
var categories = dal.Categories;
var items = new List<SelectListItem>();
foreach (var category in categories)
items.Add(new SelectListItem
{
Value = category.Id.ToString(),
Text = category.Description
});
return items;
}
}
因此,如果有人已经这样做了,并且他们认为自己正在以“正确”的方式这样做,那么我很想知道您的想法!