简体   繁体   中英

Unable to cast the type 'System.Nullable`1' to type 'System.Object' - ASP.NET MVC

ERROR

Unable to cast the type 'System.Nullable`1' to type 'System.Object'.
 LINQ to Entities only supports casting Entity Data Model primitive types.

This is the error I am getting.

Controller -

 public ActionResult FixturesAll()
 {
     teamMgr = new TeamManager();
     fixtureMgr = new FixtureManager();

     var team = teamMgr.GetTeams();
     var viewModel = new TeamIndexViewModel()
     {
          Teams = team.ToList(),
          NumberOfTeams = team.Count()
     };

     var fixtures = from fixtures in Oritia_entities.Fixtures
                    where fixtures.SeasonId == seasionID
                    select new FixtureModel
                    {

                        Team1 = "",
                        Team2 = "",
                        Winners = (fixtures.TeamWon+""),
                        FirstBattingTeam = (fixtures.FirstBattingTeam+""),
                        SecondBattingTeam = (fixtures.SecondBattingTeam+""),
                        Team1Score = fixtures.Team1Score + "",
                        Team1Wickets = fixtures.Team1Wickets + "",
                        Team2Score = fixtures.Team2Score + "",
                        Team2Wickets = fixtures.Team2Wickets + ""
                    };

      ViewData["Fixtures"] = fixtures;
      return View(viewModel);
 }

Partial View

<%@ Control Language="C#" Inherits=
"System.Web.Mvc.ViewUserControl<IEnumerable<DataAccess.FixtureModel>>" %>
    <table>
    <% foreach (var item in ViewData["Fixtures"]
 as IEnumerable<DataAccess.FixtureModel>) // Here I am getting the error
       { %>
          <tr>                 
            <td>
                <%: item.Team1 %>
            </td>
            <td>
                <%: item.Team2 %>
            </td>
          </tr>
   </table>

View

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
 Inherits="System.Web.Mvc.ViewPage<FunBox.ViewModels.TeamIndexViewModel>" %>
<ul>
    <% foreach (string team in Model.Teams)
       { %>
           <li><a href="<%: team.ToString() %>/">
           <%: team.ToString()  %></a> </li>
    <% } %>
</ul>

<div>
        <% Html.RenderPartial("FixturesAll",ViewData["Fixtures"]); %>
    </div>

Complex Classes

 public class TeamIndexViewModel
 {
     public int NumberOfTeams { get; set; }
     public List<String> Teams { get; set; }
 }

 public class FixtureModel
 {
     public string Team1 { get; set; }
     public string Team2 { get; set; }
     public string Winners { get; set; }
     public string Team1Score { get; set; }
     public string Team1Wickets { get; set; }
     public string Team2Score { get; set; }
     public string Team2Wickets { get; set; }
     public string FirstBattingTeam { get; set; }
     public string SecondBattingTeam { get; set; }
 }

Output of sp_help Fixtures

Id          bigint (pk)
TeamID1     bigint
TeamID2         bigint
TeamWon         bigint
Date            datetime
SeasonId    bigint
ManOfTheMatch   bigint
FirstBattingTeam    bigint
SecondBattingTeam   bigint
ResultDescription   nvarchar
Team1Score  bigint
Team2Score  bigint
Team1Wickets    bigint
Team2Wickets    bigint

This is my overall structure and I am getting the above error.I googled but i didn't get an exact solution for this. Any help is highly appreciated.

Thanks all for helping me and my special thanks to Jon Skeet for giving the idea

Please see my updated query

 var data = from fixtures in Oritia_entities.Fixtures
                   join t1 in Oritia_entities.Teams on new { ID = fixtures.TeamID1 } equals new { ID = t1.ID }
                   join t2 in Oritia_entities.Teams on new { ID = fixtures.TeamID2 } equals new { ID = t2.ID }
                   where fixtures.SeasonId == seasionID
                   select new FixtureModel
                   {
                       Team1 = t1.TeamName,
                       Team2 = t2.TeamName,

                       Winners = SqlFunctions.StringConvert((double)(fixtures.TeamWon ?? 1)),
                       FirstBattingTeam = SqlFunctions.StringConvert((double)(fixtures.FirstBattingTeam ?? 1)),
                       SecondBattingTeam = SqlFunctions.StringConvert((double)(fixtures.SecondBattingTeam ?? 1)),
                       Team1Score = SqlFunctions.StringConvert((double)(fixtures.Team1Score ?? 1)),
                       Team1Wickets = SqlFunctions.StringConvert((double)(fixtures.Team1Wickets ?? 1)),
                       Team2Score = SqlFunctions.StringConvert((double)(fixtures.Team2Score ?? 1)),
                       Team2Wickets = SqlFunctions.StringConvert((double)(fixtures.Team2Wickets ?? 1))

                   };

I used SqlFunctions.StringConvert for converstion to string and nows it working. Thanks all.

Instead of:

<% foreach (var item in ViewData["Fixtures"] as IEnumerable<DataAccess.FixtureModel>)

try:

<% foreach (var item in Model)

Also try to eagerly load your entities using the .ToList() method:

ViewData["Fixtures"] = fixtures.ToList();

Also you might consider using view models instead of ViewData . It will make your code much cleaner and you will no longer rely on magic strings .


UPDATE:

Try this:

var fixtures = Oritia_entities
    .Fixtures
    .Where(f => f.SeasonId == seasionID)
    .ToList()
    .Select(f => new FixtureModel
    {
        Team1 = "",
        Team2 = "",
        Winners = (f.TeamWon+""),
        FirstBattingTeam = (f.FirstBattingTeam+""),
        SecondBattingTeam = (f.SecondBattingTeam+""),
        Team1Score = f.Team1Score + "",
        Team1Wickets = f.Team1Wickets + "",
        Team2Score = f.Team2Score + "",
        Team2Wickets = f.Team2Wickets + ""
    });

Try rewriting your LINQ query:

var fixtures = Oritia_entities.Fixtures
    .Where(fixtures => fixtures.SeasonId == seasionID)
    .AsEnumerable()
    .Select(fixtures => new FixtureModel
                    {

                        Team1 = "",
                        Team2 = "",
                        Winners = (fixtures.TeamWon+""),
                        FirstBattingTeam = (fixtures.FirstBattingTeam+""),
                        SecondBattingTeam = (fixtures.SecondBattingTeam+""),
                        Team1Score = fixtures.Team1Score + "",
                        Team1Wickets = fixtures.Team1Wickets + "",
                        Team2Score = fixtures.Team2Score + "",
                        Team2Wickets = fixtures.Team2Wickets + ""
                    }
    )
    .ToList();

The LINQ query is basically the same but I've put an AsEnumerable() call in between the last criteria which can be translated to SQL (which is the Where(...), and what is the type and value of seasionID btw?), and the Select(...).

Reason is that I think L2S is somehow trying to translate the Select(..) into SQL. Not sure it will work, but worth a try.

Use this in the controller:

  ViewData["Fixtures"] = fixtures.ToArray();

I'm not sure, but I think that's where your issue is. If you don't use ToArray , then you're sending an IQueryable to the View, which could be problematic.

Give this a shot... (although id tweak the try catch a bit, if you end up using it. i wouldn't recommend suppressing an error and not doing anything about it/allow it to die a silent death ;P)

 public string NullableObjectToString(object obj)
 {
      try
      {
          if (obj == null)
              return "";

          return (obj ?? string.Empty).ToString();
      }
      catch (Exception)
      {
          return "";
      }
  }

Then

var fixtures = from fixtures in Oritia_entities.Fixtures
                  where fixtures.SeasonId == seasionID
                  select new FixtureModel
                  {                        
                     Winners = NullableObjectToString(fixtures.TeamWon),
                     FirstBattingTeam = NullableObjectToString(fixtures.FirstBattingTeam) // ..... you get the idea
                  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM