开发者

How does the Entity.DbSet.Find() method work in MVC3 context?

I'm following the MVC3 Music Store tutorial and this line of code kind of confuses me.

public ActionResult Details(int id)
{
    var album = storeDb.Albums.Find(id);
    return View(album);
}

Here is the Album.cs model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcMusicStore.ViewMode开发者_Go百科ls
{
    public class Album
    {
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }
        public Genre Genre { get; set; }
    }
}

When I visit the /Details/5 URL, how does it know to map the 'id' parameter to the Album's AlbumId attribute?

Thanks for the help.


Find is a method of DbSet, it finds an object in the DbSet based on its id. It knows the id from the mappings you declared for this class.


I was wondering the same thing and started playing with the code. Looks like Find only works on the PrimaryKey. If you change the Find value to one of the album titles in the database, such as "Nevermind", you get this error when you try to edit an album:

The argument types 'Edm.Int32' and 'Edm.String' are incompatible for this operation. Near WHERE predicate, line 1, column 74.

Since it's explicitly expecting an Int32, the PrimaryKey makes sense. What would really solve the problem is to run the Create script for the DB against a real instance of SQL Server and then run Profiler to see what sorts of queries are going to the DB.


This is a little late, but I was looking for this same answer. According to MSDN dbset.find "Uses the primary key value to attempt to find an entity tracked by the context". So it looks like it just search on the primary key.


There is no find method in Linq. There is no relation between linq and Mvc that makes linq work in a different way. It is a method of the member storeDb. So the easiest way to get to know how the find method works is inspecting the type of storeDb.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜