Operator == cannot be applied to Guid or int in Li

2019-07-23 08:53发布

问题:

Working through the WROX "Beginning ASP.NET MVC 1.0" book I've hit a strange 'error'.

"Operator '==' cannot be applied to operands of type 'System.Guid' or 'int'". The line in questions is:

(p => p.ID_Officers == id).Single();

The full code is below, and Officers is my table, ID_Officers is my ID field. (I imagine that I could of used 'o' instead of 'p')

public ActionResult IndividualOfficer(int id)
    {
        OfficersDataContext dataContext = new OfficersDataContext();
        Officer officer = dataContext.Officers.Where
            (p => p.ID_Officers == id).Single();
        ViewData["OfficerName"] = officer.OfficerName;
        ViewData["Officer"] = officer;

        return View();
    }

Any words of wisdom for this beginner would be appreciated.

I might add, that although this book was recommended for beginners - boy it's dry. It's clearly laid out, obvious to see what needs to be added/typed in during the exercises, but I feel it's written for an experienced programmer coming over to MVC. Rather than a beginner programmer.

So, does anyone know of a more beginner friendly book (I like books and reading) that I could more easily sink my time and teeth into?

Thanks for your help and guidance.

Mike

回答1:

Its very simple.

id is an int. p.ID_Officers is, as the error message states, a Guid, which is not an int and cannot be checked against an int for equality. Two different types, you know.

I'm not sure where the id of the controller method comes from. At some time you must present to the user a list of officers, and construct links that point to each individual officer which includes the p.ID_Officers in the definition of the link, but your route is expecting an int. Without seeing how your routes are configured or your officer links are constructed, I can't give you much more of a hint than that.



回答2:

Well, the problem is that p.ID_Officers is a System.Guid while the id you are comparing it to is of type int. So you can change the signature of your method to

public ActionResult IndividualOfficer(Guid id) 

And now it should be able to compile.

Another option would be to change your id column in your database schema to an int instead of a uniqueidentifier (which becomes a System.Guid in .net).