References
- http://msdn.microsoft.com/en-us/library/vstudio/cc716677(v=vs.100).aspx
- http://www.entityframeworktutorial.net
Background
I'm currently in the midst of putting together an API, using the "Class Library Project" template in Visual Studio, however I also wanted to store the data to a database using EF but EF is mostly geared towards Web Projects. How do I integrate it? My searches led me to Reference #1, above.
General Procedures
You can either follow the guide in Ref #1 above, or to get a general idea, you follow along here (I'll also give a simple example on retrieving data). Here I'm assuming you have already created a database in SQL Server.
- Create a new Solution, using the "Class Library Project" template option.
- Add a new project that will access EF in your class library, say, a Console Project (Solution Explorer --> Right-Click --> Add --> New Project)
- Add a reference to your class library inside your Console Project (Right-Click Console Project --> Add Reference --> Solution)
- Add a reference to System.Data.Entity inside your Console Project (Add Reference --> Assemblies)
- Add a Conceptual Model to the Class Library Project, i.e., Entity Framework. (Right-Click Project --> Add --> New Item --> Data --> ADO.NET Entity Data Model)
- A wizard will step you through the process of adding the tables from your existing database. You basically make a connection to SQL Server, select the tables you would like to access, and click OK.
- This will create you a .edmx file and show you a diagram of you entities (this will initially resemble your db)
- Copy your app.config connection string to the Console Project
- Open app.config in your Class Library Project --> Copy the connection string ( name usually ends in -Entities, or however you name it in the wizard, above)
- Paste into the Console Project's app.config
- Save.
- Head over to your Console Project and edit the automatically created class (*.cs) and start accessing data. Something basic like this:
Here, Team is an entity created by EF. You can see all your entities by going looking through your edmx or looking at the EF graph. dbContext is your interface to the db via the context object, and you must add an entity to the context before you can save, as seen above.
To learn more ways you can interact with EF, I highly suggest visiting the link in Ref#2, as it describes a plethora of tasks, including updating, deleting, one-to-many and many-to-many relationships with EF.
No comments:
Post a Comment