Using System.Data.Linq in a Razor view

2019-01-11 03:47发布

问题:

I may have a fundamental misunderstanding of what is going on here, but I'm having an issue looping through a LinqToSQL class in my razor view:

<h3>Owners</h3>
@foreach (var ThisOwner in Prop.PropertyOwnerships.Where(p=p.bIsOwner.Value==true))
{
<div class="ODEditEntry">
...

I'm getting the following error:

Compiler Error Message: CS0012: The type 'System.Data.Linq.EntitySet`1' 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 tried putting @using System.Data.Linq at the top of the cshtml file but it is telling me that Linq doesn't exist in the System.Data namespace. This is obviously not true and, yes, I do have system.data.linq as a reference in my project.

Any Ideas here? Is a import needed? Can I just not do Linq style stuff in my razor views? That would seem....odd?

回答1:

You need to import the namespace into your view by adding @using System.Data.Linq at the top of your view. However if you want it in all your views then you need to add <add namespace="System.Data.Linq" /> to the web.config in your Views folder:

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Data.Linq" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Although not relevent to your question you should really try to move this logic out of the view and into the controller, it will make things much easier to debug and means that your presentation is separated from your business logic.



回答2:

What fixed it for me was to right click the System.Data.Linq assembly reference, then hit properties. In there set Copy Local to true.



回答3:

Does your Linq-to-Sql datacontext exist outside of the web project (e.g. in another class library)? If so, where you have added a reference to that project it all builds fine, but in the Razor view you are trying to directly access a type from the System.Data.Linq assembly without referencing it in the web project. Try adding the reference to the main web project and see what you get.



回答4:

You need to add a reference to System.Data.Linq in your project and/or in your Web.config.