开发者

ASP.NET MVC Razor View, not correctly showing Linq to SQL related entities

I'm using Linq to SQL in an ASP.NET MVC3 project with Razor views.

My L2S objects seem to work fine in controller/model code; I can reference and work with child class collections for my 开发者_如何学Pythonrelated objects. However, I am unable to do so in my Razor views. Intellisense recognizes the child class collection:

Model.ChildObjects

But it is unable to provide any code completion for the ChildObjects object itself. Trying to use the collection as a collection like so:

foreach(var item in Model.ChildObjects)

results in the following inline error in the editor:

foreach statement cannot operate on variables of type
System.Data.Linq.EntitySet<ChildObjectType> because 
System.Data.Linq.EntitySet<ChildObjectType> does not
contain a public definition for 'GetEnumerator'

There seems to be something wrong with what is being referenced from the Razor view. When I try to use code like this:

@Model.ChildObjects.Count()

I get this compilation error upon executing:

The type 'System.Data.Linq.EntitySet`1<T0>' is defined in an assembly that is
not referenced. You must add a reference to assembly 
'System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I haven't changed anything in the web.config file(s) for the project. I have recently updated my Windows 7 to SP1, and updated my NuGet... but I'm not sure if there would be anything involved there.


I don't know the reason for this, and will therefore leave this question open for a bit in case someone can explain why what I did worked;

I found this question: Using System.Data.Linq in a Razor view

In it, someone mentions setting the reference to System.Data.Linq to 'Copy Local' = true. Doing that has solved the issue I am experiencing here.


Try adding the namespace System.Data.Linq in the web.config in the views folder.


Although you seemed to have solved your issue, I think the potentially bigger issue is that you are passing domain models to your view. I'd recommend against that, as it makes your view files specifically dependent on your data layer.

It would be better to create view models that contain the information the view requires. The controller would become responsible for selecting data through your data layer and transforming it into view models, which you can then add your validation attributes to. It's a much cleaner design.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜