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.

Prerequisites

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.

tmp1867

Enter your new schema name and select Ok.

tmpB89E

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`)

) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

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`)

) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

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.

tmpF6A8

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

tmp5A7A

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

tmp6D96

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.

tmpAEC3

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.

tmp4C6A

Select Finish and the EF magic happens.

tmpE92C

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)

    {

        mySqlEntities.AddToProductSet(product);

    }

    public void Delete(Product product)

    {

        mySqlEntities.DeleteObject(product);

    }

    public void Save()

    {

        mySqlEntities.SaveChanges();

    }
}

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)

    {

        mySqlEntities.AddToCategorySet1(category);

    }

    public void Delete(Category category)

    {

        mySqlEntities.DeleteObject(category);

    }

    public void Save()

    {

        mySqlEntities.SaveChanges();

    }

}


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.

Source

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
    and

  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
    bad

  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.
    Thanks

    wondershare-dr-fone

  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…

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