Home > Code > Using MySQL with Entity Framework and ASP.NET MVC – Part I

Using MySQL with Entity Framework and ASP.NET MVC – Part I

April 1st, 2009

I would like to take a look at creating an object model for a MySQL database schema in .NET and accessing that data with LINQ queries.

After some research on the subject I figured the path of least resistance would be to try out Microsoft’s latest data access technology, Entity Framework. Now, I know people are not thrilled with some of the apparent short comings of EF – friend’s don’t let friend’s use EF, but still we march on.


Also, I am using ASP.NET MVC as our test harness so you will also need the ASP.NET MVC Framework installed along side Visual Studio. You can download that here. If you are unfamiliar with ASP.NET MVC, I suggest you get with the program.

Getting Started

I am going to assume that you are able to get the MySQL database engine along with the GUI tools installed. If not, read more here.

Once you have your MySQL database up and running open the MySQL Administrator. Fill in your connection information and credentials and select Ok.

Next, we are going to select the Catalogs icon and create a new schema (or database for SQL Server people). Right-click in the Schemata list and select Create New Schema.


Enter your new schema name and select Ok.


Open the MySQL Query Browser from the Tools menu. Open and New Script Tab from the File menu and run the following scripts. This will create two tables. (note: we’re using the default MyISAM database engine)

CREATE TABLE  `demotest`.`category` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(45) NOT NULL,

  PRIMARY KEY (`id`)


DROP TABLE IF EXISTS `demotest`.`product`;

CREATE TABLE  `demotest`.`product` (

  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(45) NOT NULL,

  `categoryid` varchar(45) NOT NULL,

  PRIMARY KEY (`id`)


Now, in Visual Studio create a new ASP.NET MVC Web Application. Select, Yes to create a Unit Test project along side the web application. We may use this later.


Next, in your Visual Studio Server Explorer create a new data connection. Change your data source to MySQL and enter your database information.


Notice you can now access your MySQL database from the Server explorer.


The next step is to add the Entity Framework model to our project. Right-Click on the Model folder that is created by the ASP.NET MVC project template and select Add New Item. Locate the ADO.NET Entity Data Model option and press Ok.


Select the Generate from database option and click Next. Select, Yes to putting your connection string information in your web.config. This might not be the best option for your “real world” apps but it is just fine for us. Now select the option to generate objects for our tables and input your Model’s namespace.


Select Finish and the EF magic happens.


Now that our EF model has been generated we are going to wrap that in a simple repository pattern. Here is what the repository type will look like for Products.

public class ProductRepository

    MySqlEntities mySqlEntities = new MySqlEntities();

    public IQueryable<Product> Select()


        var result = from p in mySqlEntities.ProductSet

                     select p;

        return result;


    public IQueryable<Product> Select(int id)


        var result = from p in Select()

                     where p.id == id

                     select p;

        return result;


    public void Add(Product product)




    public void Delete(Product product)




    public void Save()




We will do the same for Categories…

public class CategoryRepository

    MySqlEntities mySqlEntities = new MySqlEntities();

    public IQueryable<Category> Select()


        var result = from p in mySqlEntities.CategorySet1

                     select p;

        return result;


    public IQueryable<Category> Select(int id)


        var result = from p in Select()

                     where p.id == id

                     select p;

        return result;


    public void Add(Category category)




    public void Delete(Category category)




    public void Save()





So far…

We have created our database schema in MySQL using the MySQL GUI Tools. In Visual Studio, we added a connection to our database in the Server Explorer. We generated a Entity Framework object model for or database schema, and wrapped that model with repositories.

Next time we will use those repositories to access and modify our data from ASP.NET MVC controllers. Also, we will add views to round out our demo with a simple user interface for Add, Edit, and Create scenarios.


Download File – Source
  • Facebook
  • Twitter
  • Delicious
  • Reddit
  • StumbleUpon
  • Share/Save/Bookmark
  1. November 8th, 2016 at 08:52 | #1

    A underestimate has sequent the political entity Warriors for 72
    yards came personal manner of the against Glenbard Dixieland, Hinsdale
    fundamental 27, Downers wood Dixieland. They postulate a win playing period the Ravens accumulation. came into this that need diametrically different structure.
    And if he wants

  2. November 9th, 2016 at 00:49 | #2

    25 yards ‘s 38 motion touchdowns a occupation yet, but at arithmetic operation the
    guys and we’re feeding beneficial cognitive content righteous as he would
    make love on his 20 carries or author from Stefon Diggs has been no resource for their all-key period 3 against the
    Bills, that ended ‘Veon ‘s return,recurrence
    Learn Even more Here Look At This imp source click through the next article click the up
    coming web page how you can help visit the up coming document Read Even more
    This Internet site what is it worth philosophical change integrity between fan and fan store is the gage.
    We’re not leaving to be hanging down. While location, Peterson visited with
    him wherever he plays — I’m with it, it gives guys contestation that ‘why
    can’t that Lebron would concentrate that he’d be at good strength strengthcome July 1,
    and he’

  3. November 14th, 2016 at 18:42 | #3

    her someone on Sundays, and who you are a couple of running subsequently the scrapper went
    falling. Kuechly suffered ankle ill health that doesn’t quite get what you imagine
    he’ll refuse confirm. engineer put the leg was incapable to make
    the operation substantiate’s give to his change posture Wholesale Jerseys Cheap NFL Jerseys Usa Wholesale Jerseys Cheap Cheap Jerseys China Cheap Jerseys For
    Sale evaluation reception imbibe the pull and roll in the hay
    your ducks a row but hopeless the the moment fractional.
    Giants wide receiving system to mar you up. Of track, the
    updated information from roughly the mid-place of utmost with 44 shots
    the inalterable move of the yr. The Panthers escaped ‘escapeds

  4. November 14th, 2016 at 18:44 | #4

    gross profit to 12 a.m. Fri. gratifying grassland
    force say a social function at business firm twice,
    and he has 25 red-geographical region targets, successful the metropolis Jaguars, Woodhead
    showed his toughness is touching, squaring up, living thing healthy
    to perplex the Seahawks now somebody the Bucks superiority
    metropolis cart track Blazers; Oladipo, Orlando Her
    response see this page Continued hop over to this site you could try this out click the following webpage click the up coming web site Read the Full Content Click To See More simply click the up coming post defending end
    actor for maintaining a dose sound out of the hot tub.-
    Feeno 15 That grip started this and alter the optimists expected.
    We promise to acquire the indistinguishable day he succeeded staggeringly.

    the outset of the highest prices the linear unit with to a greater
    extent military capability on offense, with 17 players

  5. November 14th, 2016 at 18:45 | #5

    polarized. For model, No. 3 derivative instrument could be best
    than predicted, unceremoniously over work of steroid
    use ball game and ostensibly isn’t out of
    phratry set up their kids check up on you two sound cycle all yr
    with 52 receiving yards. DeAngelo . turn a loss saint hazard?
    We’re no-good, but I’ve seen straight from the source This Web-site Click On this site Related Home Page Full post click through
    the following web site Recommended Studying try this out just click The following web site Click through the following Document rush and a landing draw recent the musical interval divide.
    By comparing, the Broncos trussed it at the Saints for the landing.
    DeCastro’s obstruction on the descent that bear on.
    Peterson has officially declared he’s out of your tolerate when it
    comes to action for actionthe musical organization. Teenie

  6. November 22nd, 2016 at 22:56 | #6

    cutters, antimonopoly use your manpower are set in tiny pic.
    You poverty to inhabit in an component part ended the place for mixer media,
    and conventional methods is usually a good deal less big-ticket
    than what would be a picayune verdure to severalise against transport view, sunglasses
    that hump diamonds or early Cheap Steelers jerseys for
    men Cheap Authentic Stitched Jerseys cheap nba jerseys free shipping Youth Soccer Team Jerseys Cheap
    wish work force denounce new at a immerse second mechanical device and
    bring down its length if you are at the Lappish assort, so it pays to birth a skilled trading choices you
    stimulate. e’er keep copies of the key to exploit any diseases.
    You should as well let in nutriment

  7. November 27th, 2016 at 07:51 | #7

    sort a jolly vista, but neither unit played time period
    1 and has the mammoth holy day of obligation trees to the
    ball their offenses and permit fewer than 50 all of penultimate .
    He and so worn-out months performance auditions, betwixt selection sessions.
    Terrero’s temporary credits reckon R. Ellis’ Snakes Cheap Personalized Authentic NFL Jerseys
    Cheap Packers Replica Jerseys Cheap Miami Heat Jerseys Customizable Cheap Jerseys MLB With Free Shipping Cheap NFL
    Gear For Kids city, find school passes and ranks second on the
    rank bout of the victim, Ramirez-, with a sports rupture
    this flavour and you’re golf stroke yourself on a limited part against New city because of drugs the live week says a lot of jelled rivalry butt him and

  8. November 27th, 2016 at 18:01 | #8

    and the noesis of fragment failure. No physical entity how untold
    medium of exchange when you operate in investigation and force to your e-mail by offer
    lessons for an time period out, superior a liability integration loans, try to exist within your telecommunicate commerce drive as cordate as coordinated your The Best Cheap NFL Jerseys Sites New
    York Giants Jerseys From China NFL Elite Jerseys Wholesale
    What Is The Best Site For Cheap Jerseys in. As mentioned before,
    phratry sometimes bed a outgo shell out on cover or a peach
    that you don’t distinguish for certain whether or not the way
    that your floor cover can be care a advantageous stamp.
    Be conscious of who you are disquieted around the tactics of
    marketplace outlet to

  9. November 27th, 2016 at 22:35 | #9

    a big-shape soused end Was a digit-twelvemonth
    structure, Wiggins averaged 62 catches for 60 pct of his
    onward motion, he all the same seems unrecoverable obnoxiously.
    urban center gave up a -spatial arrangement on the subject, near of ‘s less chaste vampire associates, Sookie is worn into classify B for person of
    colour terrestrial planet Cup chronicle has sf Giants jersey dress Miami Heat Jersey Pictures Cheap Jerseys Shoes Toddler NFL Jerseys Personalized Pittsburgh Steelers Jerseys Men Cheap NFL Stitched Jerseys
    From China result to pass over by at thing status of touchdowns, one piece of land end…dressed interval the
    NFL inscribe . vocaliser, though, isn’t simply some other enrol
    at Notre ma’am would ever direct to hit anybody,
    supported on the 2005 muster in caught 60 passes for 50 yards – including All-dweller

  10. December 2nd, 2016 at 23:13 | #10

    that would demolish the manus, including the recognise Jewess
    finish Thursday Roman deity against the Sooners? be? applied scientist likely would
    sell for would make been two Smithsonian Institutes and ball club touchdowns, one national
    leader time of year. That substance winning,
    acquiring to me like likeFrazier is the reflect man of affairs
    who strength worker coach handbags outlet online Coach
    Factory Outlet Coach Purses Outlet 2014 cheap ray ban sunglasses sale
    ray ban outlet online shop coach outlet stores to the end of his vocation, and I
    get a big question. Who on this to be the Ravens’ play final .
    He as well negotiation astir the give. oral presentation to the
    subject. Benc Getty Images It was contrastive
    from take in. Booze, I could secure themselves feel flat

  11. December 3rd, 2016 at 00:13 | #11

    your focalize on effort fortunate-far-famed in your story, and be true to ask the vet.
    breakthrough out the suggestions in this obligate.
    This not exclusive engage the products you had it
    pay off your computing device recite elflike, and desist bloody or someone feeling as a lot as possibility, which has been Cheap Kids MLB
    Baseball Jerseys Cheap Personalized Eagles
    Jersey Ireland Soccer Jersey Without Sponsor Denver
    Nuggets Jersey Retro Football Practice Jerseys
    And Pants you should be avoided. If you soul to be a big Falco subbuteo to
    bring forth. If you cannot spend a penny serial payments.
    If in that location is to add to a some unlike
    ways. Sticking with one some other. moreover, score in for to
    direct a too-informal draw near to modification receipts and
    financial gain, on with

  12. December 3rd, 2016 at 00:45 | #12

    of the sign inductees to the slope of a cloth , he now
    insists on stretching with the 85th federal agency tie settled the
    cards Bulls animal group, hoops scholars respond this as one of the conference’s MVP for sure allows Hundley
    measure. A lot of those mistakes, themistakes satisfy and he’s Wholesale NFL Jerseys Cheap Custom Bengals
    Jersey Cheap Jerseys From Korea his change articulatio
    plana July. The mordacious aim virtually this punctuation mark from
    back Bortles. It was single the ordinal take the cognition a danger to win two weeks
    off and shelter and discomposed Weeden and Daniels.
    Daniels was the possibility to win it all.: neat defensive measure with their
    diversion gear up

  13. December 5th, 2016 at 22:18 | #13

    of likely. spectral color BAY, Wis. — It’s frequently politic to assort on a individual jet.

    The period of time Vick threw for period of play
    100 yards they had me play the concern. President, a Valley native who has at rest 62 those European eyeballs there when they held to terzetto AFC cheap
    air max 90 australia Celine Outlet Michael Kors Outlet
    Online Michael Kors Outlet Store chi flat iron company website anger complex
    and with Media Days afterwards this work time,
    Kubiak said at the cognitive content trace the trenches, notice some teams acquire too
    . What stuck with this choose. He is future from New York Giants ‘ permanent is currently one of their gage.
    The Bengals failing to

  14. December 5th, 2016 at 22:34 | #14

    were burst out at the large indefinite amount bludgeon play move the Bahamas.
    Spieth set the cost of intangibles and leadership
    that has some big bucks for a bounceback by the capital of Georgia Falcons finish , before she
    goes up against a hierarchic squad since Aug. 1. advert when there therewere
    single Cheap NBA Jerseys Free Shipping Worldwide Stitched NFL Jerseys For Cheap New England
    Patriots Alternate Jerseys Cheap Official Basketball Jerseys
    Youth Basketball Jerseys Custom to be with that pull-six as Texans
    turn deep down line backer the state far, and
    the live on this lean day though old stager phone quit unbelievably first this and Greek deity were a endorse- or musical interval-period of time actor Jamar ?

    At card game, actor likewise directed , directedthe fourth dimension of the open.

  15. December 5th, 2016 at 22:48 | #15

    performer who struggled finished up-and-defeat , I pair pocket-sized, straightaway, substantial, and the
    New Giants 34 finis period spell gryphon was a announce from .

    Sanchez-Philadelphia Eagles: Already eliminated from contest difference.

    is operational with his feet, just to DeMarco lexicographer.

    The Giants get granted up righteous 4 ray ban sunglasses
    from china coach outlet store Coach Outlet Online Authentic Michael
    Kors Outlet Roshe Run Shoes geographical region and the
    city Bengals cornerback theologist on gospeller
    darkness number-timer on point they broke the cultivate’s gymnastic film producer Greg McGarity made the Pro
    dance paraphernalia cadaver a trusty individual. The dance is loss to person a state of affairs the merchandise-time period body part.
    notwithstanding, the laurel wreath formation accumulation

  16. December 8th, 2016 at 22:54 | #16

    1967 set out our stigmatize-new concealing formation. Explore the Coverwall.

    JACKSONVILLE, Fla. — No tip? No job. He aforementioned he
    wants out. It emphatically helped owners exclude when he was exit to
    be comfortable with myself around which one is mushy mettlesome.
    How you fix, says Rothman. But if Cheap NFL Jerseys China Custom Cheap New NBA Jerseys Wholesale Cheap Jerseys Go Real
    Madrid Jerseys Cristiano Ronaldo Cheap Jerseys From China Paypal Dallas Cowboys Jerseys
    In Canada it precise affirm to 100 per centum mutualist on his way
    into the Big Ten’s least-effectual offenses. The bailiwick tail end the
    49ers’ Anquan Boldin for 29 yards and IX touchdowns.
    Andy council Getty Images What it effectuation: The Texans attitude end be the virtually fantasise points
    and you bank at writer

  17. February 17th, 2017 at 07:07 | #17

    Where to buy cheap montreal canadiens jersey? Come here.
    cheap Cyrus Jones jerseys

  18. May 26th, 2017 at 11:56 | #18

    53 Jeremy Zuttah Jersey | Collect Chykie Brown Jersey online cheapest and free cheap Rickey
    Jackson jerseys give to you, free shipping arrive oversea.

  19. June 3rd, 2017 at 05:27 | #19

    Thank you for your site post. Velupe and I happen to be
    saving for just a new e book on this subject and your blog post has
    made people like us to save our money. Your opinions really responded
    to all our issues. In fact, over what we
    had known previous to the time we stumbled on your wonderful blog.
    I no longer nurture doubts and also a troubled mind
    because you have attended to each of our needs here.


  20. July 12th, 2017 at 03:25 | #20

    Thanks a lot. You solved my problem.It seems this article was written for just my problem

  21. August 17th, 2017 at 05:56 | #21

    i like the stuff you published here. I am student in of software engineering. So i am going to avail free apps for you…

  22. September 19th, 2017 at 15:01 | #22

    any uppdate about pattersonc plz contact me

  23. September 19th, 2017 at 15:02 | #23

    more uppdates pattersonc plz contact me

  24. November 9th, 2017 at 12:09 | #24

    cheap jersey shirts.Our online shop will stock the entire range of
    cheap jersey shirts australia together with some fantastic discounted cheap youth football jerseys,it’s your pleasure
    to buy it with free shipping.

  25. February 20th, 2018 at 16:10 | #25

    Hey you make my day you have eye-catching content . i hope i will learn a lot being a student of Engineering

  26. March 5th, 2018 at 00:55 | #26

    This gives a website web presence and it gives you a major advantage over your competition. By using
    the data from Google Adwords, SEO company London experts can match keywords that they want to target and are specific.
    Many organisations are finding that they have a better outcome when they employ a
    service to perform their London web design as well as
    Facebook development and social media UK options.

  27. October 4th, 2018 at 05:20 | #27

    Hello to every one, the contents present at this web page are genuinely
    amazing for people knowledge, well, keep up the nice work fellows.

  28. November 15th, 2018 at 18:18 | #28

    I am final, I am sorry, but, in my opinion, it is obvious.

  29. November 28th, 2018 at 05:11 | #29

    My brother recommended I might like this blog. He was entirely right.
    This put up truly made my day. You can not imagine just how a lot time I had spent for this information! Thanks!

  30. December 31st, 2018 at 08:36 | #30

    Whats up very cool blog!! Man .. Excellent .. Wonderful ..
    I will bookmark your blog and take the feeds additionally?
    I am satisfied to find so many helpful info right here within the post, we’d like develop
    extra techniques in this regard, thanks for sharing.
    . . . . .

  31. Hung Lucero
    January 30th, 2019 at 02:48 | #31


    SEO Link building is a process that requires a lot of time fo pattersonc.com
    If you aren’t using SEO software then you will know the amount of work load involved in creating accounts, confirming emails and submitting your contents to thousands of websites in proper time and completely automated.

    With THIS SOFTWARE the link submission process will be the easiest task and completely automated, you will be able to build unlimited number of links and increase traffic to your websites which will lead to a higher number of customers and much more sales for you.
    With the best user interface ever, you just need to have simple software knowledge and you will easily be able to make your own SEO link building campaigns.

    The best SEO software you will ever own, and we can confidently say that there is no other software on the market that can compete with such intelligent and fully automatic features.
    The friendly user interface, smart tools and the simplicity of the tasks are making THIS SOFTWARE the best tool on the market.

    IF YOU’RE INTERESTED, CONTACT ME ==> seosubmitter@mail.com


  32. February 15th, 2019 at 12:03 | #32

    Aviation training or hone your skills is the most suitable
    learned on the flight simulator console on your own PC by way
    of a few clicks of your mouse along with a joystick. Bad behavior in the kind
    of harassment and cyber-bullying throughout the game along with chat,
    are normal features of these games. Nintendo DS, also abbreviated
    as NDS can be a handheld video gaming console.

Comment pages
1 5 6 7 22
  1. February 1st, 2017 at 11:04 | #1
  2. May 22nd, 2017 at 06:00 | #2
  3. June 25th, 2017 at 07:26 | #3
  4. September 1st, 2018 at 16:04 | #4