Results 1 to 21 of 21

Thread: Tutorial: An Introduction to the ADO.NET Entity Framework

  1. #1

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Tutorial: An Introduction to the ADO.NET Entity Framework

    This is the VB.NET version of the ADO.NET Entity Framework Tutorial. (C# version on Codeguru.com)

    An Introduction to the ADO.NET Entity Framework

    Database development with the .NET framework has not changed a lot since its first release. Many of us usually start by designing our database tables and their relationships and then creating classes in our application to emulate them as closely as possible in a set of Business Classes or (false) "Entity" Classes, and then working with them in out ADO.NET code. However, this process has always been an approximation and has involved a lot of groundwork.

    This is where the ADO.NET Entity Framework comes in; it allows you to deal with the (true) entities represented in the database in your application code by abstracting the groundwork and maintenance code work away from you. A very crude description of the ADO.NET Entity Framework would be "It allows you to deal with database concepts in your code."

    Of course, it's much more than that, but in this tutorial, instead of starting with a lengthy spiel about the Entity Framework and how it differs from LINQ to Sql, you will code first, talk later.


    Contents

    In this tutorial, you will go over the following:

    1. Set up the environment and database, generating the Entity Data Model
    2. Basic ADO.NET Entity Framework operations with a form for Payrolls
    3. Adding a little efficiency using another form for Authors
    4. The case for using stored procedures in the Entity Framework
    5. Using stored procedures to perform SELECT operations against the database in the Articles form
    6. Using stored procedures for the INSERT, UPDATE, and DELETE operations in the Articles form
    7. More information and conclusion



    Setting Up Your Environment

    For this ADO.NET Entity Framework tutorial, you will need the following:
    • SP1 for .NET Framework 3.5/Visual Studio 2008 (which you can download here.)
    • Some VB.NET knowledge, because the code samples here are in VB.NET
    • A little prior knowledge of ADO.NET and SQL
    • Approximately 250ml to 350ml of trimethylxanthine, otherwise associatedly known as coffee



    Setting Up the Database

    The Sample Project File - SodiumHydroxideVB

    You can either create your own project, or refer to the project files linked to above, but I would recommend starting your own and glancing at the attached project files if you need to. Before you start coding, though, you will need to create the database and its objects that will be used and referred to in this tutorial. The DatabaseScript.zip file contains a .sql script that you need to run against your SQL Express or SQL Server database; this script will generate the database for a theoretical publishing company, inventively named PublishingCompany, and the tables and stored procedures required.

    Note: You don't need to use SQL Server. You can use any database you'd like, but then you will need to modify the script to work with the SQL implementation for your database. For the purposes of this tutorial, I will continue to refer to SQL Server as the database.


    Generating an Entity Data Model in Your Visual Studio Project

    Once you are satisfied that the database has been created and you have had a look through all of the tables and its fields, start by creating a new Windows Forms Application project. I suggest the name of the solution to be SodiumHydroxide. I chose this name because I'm hoping that this project will serve as a good base for your learning. (Chemistry pun alert!)

    The very first step is to generate your Entity Data Model from the database that you created earlier; this will serve to be at the core of all your ADO.NET Entity Framework operations. To do this, right-click on the project and add a new item. Add an "ADO.NET Entity Data Model" and call it PublisherModel.edmx to correspond to your database.



    The Entity Data Model Wizard shows up and you now can use this to query your database and generate the model diagram, as long as you supply it with the right credentials. In the Wizard, click "Generate from Database" and click Next.



    Supply it with the right server name, authentication, credentials, and the database name PublishingCompany.



    Yes, I do like to name various entities on my home network after arcane Mesoamerican civilizations. Finally, "Save entity connections settings in App.Config as" should be PublishingCompanyEntities.




    In the next dialog box, choose all of the options—tables, views, and stored procedures—and the model will be generated for you. You should end up with this:



    This is a graphical representation of the Entity Data Model (EDM) that's generated by the wizard. Note that it isn't exactly a table mapping in the database, but it looks close. You'll also see that the Author entity has an article reference and payroll reference, even though you haven't actually created fields in the Author table; this relationship was derived from the foreign key constraint by the EDM generator.

    If you are like me, you probably want to know what's happening behind the scenes; you can right-click on the .edmx file in Solution Explorer and choose to view it with an XML Editor. Even if you aren't interested, I would encourage you to look at the XML anyways, because advanced Entity Framework operations will require you to directly edit the XML file, but not for this tutorial. As you can see, the EDM is essentially an XML file that's generated from the database schema, and which is understood by the Visual Studio designer to give you a graphical representation of your database entities.

    Next, you will start working on the first form with basic Entity Framework operations.

  2. #2

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Basic ADO.NET Entity Framework Operations

    Simplest stuff first; now that you're set up, you can start by creating a form to traverse through all the payrolls. To do this, you'll need a combobox that will enumerate the author names, a label, and a textbox to display the details of that author's payroll if it exists (keep in mind that some authors may not be on the payroll). Start by creating a form like this:



    Name it PayrollView and give the controls appropriate names. For now, you'll just populate the combobox with the author names. In the form's code, at the top of the class, add this (instantiate the PublishingCompanyEntities object)

    vb Code:
    1. Dim publishContext As New PublishingCompanyEntities
    2. Dim currentPayroll As New Payroll

    In the form closing event, always dispose it.

    vb Code:
    1. publishContext.Dispose()

    This PublishingCompanyEntities object — publishContext — is very important; it serves as the basis of all the ADO.NET Entity queries that you will be using. To watch it at work at its most basic level, populate the combobox with a list of authors. In the form's load event, add this:

    vb Code:
    1. 'This is a simple ADO.NET Entity Framework query!
    2. authorList.DataSource = publishContext.Author
    3. authorList.DisplayMember = "FirstName"

    In the code above, authorList is the name of the combobox. Press F5 and watch the form load. You should see the combobox with the author names in it! Loop through that list for a bit and marvel at your handiwork.



    Behind the scenes, when you set the DataSource and DisplayMember of the combobox to the publishContext.Author property, the publishContext performed the query against the database and returned the results for the combobox to use. You didn't have to open a connection or create a command; the housework was taken care of by the publishContext object.

    Now, you can populate the textboxes that represent the payroll properties for each author. Handle the combobox's SelectedIndexChanged event. Add this code to the event:

    vb Code:
    1. Dim selectedAuthor As Author = CType(authorList.SelectedItem, Author)
    2. Dim selectedAuthorID As Integer = selectedAuthor.AuthorID
    3.  
    4. 'Using Linq to Entities
    5. Dim payrollQuery As IQueryable(Of Payroll) = From p In publishContext.Payroll _
    6.                                              Where p.Author.AuthorID = selectedAuthorID _
    7.                                              Select p
    8.  
    9. Dim selectedPayroll As List(Of Payroll) = payrollQuery.ToList()
    10.  
    11. If (Not selectedPayroll Is Nothing AndAlso selectedPayroll.Count > 0) Then
    12.     currentPayroll = selectedPayroll.First()
    13. Else
    14.     currentPayroll = Nothing
    15. End If
    16.  
    17. PopulateFields()

    In the code above, you do the following:

    1. Get the current Author object from the combobox by looking at the SelectedItem property.
    2. Use a LINQ-to-Entities query against publishContext to filter the Payrolls on the AuthorID.
    3. The return type for the LINQ-to-Entities query is IQueryable<>, which you convert to a List<>.
    4. Check whether it has values and get the first row from the returned results because you only want one author's payroll.
    5. Assign this value to the currentPayroll object which then is used in your common PopulateFields method.


    The PopulateFields method, shown below, simply reads the properties of the Payroll object and places the value in corresponding labels/textboxes.

    vb Code:
    1. Private Sub PopulateFields()
    2.  
    3.     If Not currentPayroll Is Nothing Then
    4.         payrollIDLabel.Text = currentPayroll.PayrollID.ToString()
    5.         salaryUpDown.Value = Convert.ToDecimal(currentPayroll.Salary)
    6.         addButton.Enabled = False
    7.         deleteButton.Enabled = True
    8.         updateButton.Enabled = True
    9.     Else
    10.         payrollIDLabel.Text = "Not on payroll"
    11.         salaryUpDown.Value = 0
    12.         addButton.Enabled = True
    13.         deleteButton.Enabled = False
    14.         updateButton.Enabled = False
    15.     End If
    16. End Sub

    Run the application again, and when you select different authors from the combobox, you should get their corresponding salaries. You'll also see that the "Add" button is disabled for authors with payrolls, and enabled for authors without payrolls.

    Coding the Update and Delete buttons

    Because this is a simple example, the only property that the user can modify is the author's Salary. In the Update event, set the currentPayroll's Salary property to be the value of the numeric up-down control. Then, simply call the SaveChanges method on publishContext. Here is the Update button's click event:

    vb Code:
    1. currentPayroll.Salary = Convert.ToInt16(salaryUpDown.Value)
    2. Dim rowsAffected As Integer = publishContext.SaveChanges()
    3. MessageBox.Show(rowsAffected.ToString() + " changes made to the table")

    The SaveChanges method is akin to the dataadapter's Update method in regular ADO.NET; it will go through the collection of objects for 'marked' entities, and then update them in the database.

    In the Delete button's click event, use the publishContext's DeleteObject method before calling SaveChanges().

    vb Code:
    1. publishContext.DeleteObject(currentPayroll)
    2. publishContext.SaveChanges(True)
    3. currentPayroll = Nothing
    4. PopulateFields()

    You called the DeleteObject method, passing it the current Payroll object, which marks it for deletion. You then called the SaveChanges method that performs the deletion.

    Run the form again. Update a few salaries and try deleting one or two payrolls. Note that this method will delete the payroll associated with an author; it will not delete the author itself.

    Coding the Add button

    The Add button's click event will require a little more code. You first must create a brand new Payroll object, assign it values, and then call the AddToPayroll() method of the publishContext. The AddTo<EntityName> methods are generated by the Entity Framework based on the entities it generated from the database—all entities have one. It will perform the INSERT against the database and return the PayrollID of the new row in the table.

    vb Code:
    1. Dim newPayroll As New Payroll()
    2. Dim selectedAuthor As Author = CType(authorList.SelectedItem, Author)
    3. newPayroll.Author = selectedAuthor
    4. newPayroll.Salary = Convert.ToInt16(salaryUpDown.Value)
    5.  
    6. publishContext.AddToPayroll(newPayroll)
    7. publishContext.SaveChanges()
    8. currentPayroll = newPayroll  'newPayroll.PayrollID now matches the database table!
    9.  
    10. PopulateFields()

    Because PopulateFields is called right at the end, you will see that after you add a new Payroll to the database, the PayrollID label has been filled with the new value. Again, the Entity Framework has taken care of the new ID and assigned it to newPayroll.PayrollID for you to use.

    Run your form and, if you haven't deleted any authors yet, do so now. Once you delete the author, their ID label will say "Not on payroll" and their salary will be 0. Modify the salary and click "Add". Your form now displays authors and their payrolls, and allows you to add, update, and delete payrolls. Have a play with it and marvel at your handiwork again before you continue.



    Next, you will use the same concepts learned here, but with a little more efficiency.

  3. #3

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Adding a Little Efficiency

    In the Payroll form, every action performed meant one database call to get the data. For the Authors form, you will use almost all of the same logic as the Payroll form, but take a slightly different approach; we will minimize the number of database calls made by getting all the authors in one call and saving the data changes together. It will feel a little clumsy doing this, but it's only to show you how you can take another approach for basic operations in the Entity Framework.

    Create a new form for Authors that looks like this. It has a previous, next, first, last, update, and add new button. The "Clear for new Author" button will simply empty out the controls and "Create New" button will work off it by creating the Author object.



    Agreed, not the most intuitive interface, but this is just a tutorial. The "Send to Database" is the only button that will make a database call; the rest will manipulate the Author objects.

    As before, create the PublishingCompanyEntities object and instantiate it in the form load event. This time, declare a List<Author> as well; this is what you will use to hold the authors. Also, add an indexing integer to hold your current 'position'.

    At the top of the class:

    vb Code:
    1. Dim publishContext As New PublishingCompanyEntities
    2. Dim authorList As New List(Of Author)
    3. Dim currentAuthorIndex As Integer = 0

    Back in the PayrollView form, you got all the authors using publishContext.Author. This is actually an ADO.NET Entity Query Builder method expression. Query builder methods allow you to use various methods to filter the data you get back. You will read more on these methods later, but for now you should know that the result of most query builder method expression is an ObjectQuery<>, ObjectResult<>, or IQueryable<>. These classes represent the returned entity collections for the queries you perform. You will read more about these later. For the sake of variety, you will use an ObjectQuery<> next. You will get all the authors from the database, except for anyone named Mark, because you don't really care about Mark. For business logic reasons, of course.

    vb Code:
    1. Dim authorQuery As ObjectQuery(Of Author) = publishContext.Author.Where("it.FirstName <> 'Mark'")
    2. authorList = authorQuery.ToList()
    3. PopulateFields()

    Now you have a list of Author objects that you can manipulate in your form. The PopulateFields method will look slightly different.

    vb Code:
    1. Dim currentAuthor As Author = authorList(currentAuthorIndex)
    2. firstName.Text = currentAuthor.FirstName
    3. lastName.Text = currentAuthor.LastName
    4. articleCountLabel.Text = currentAuthor.Article.Count.ToString()
    5. authorIDLabel.Text = currentAuthor.AuthorID.ToString()

    You are traversing the List<>, an in-memory object. The previous, next, first, and last buttons are now easy to implement.

    vb Code:
    1. Private Sub firstButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles firstButton.Click
    2.     currentAuthorIndex = 0
    3.     PopulateFields()
    4. End Sub
    5.  
    6. Private Sub previousButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles previousButton.Click
    7.     If currentAuthorIndex = 0 Then
    8.         MessageBox.Show("No previous author")
    9.     Else
    10.         currentAuthorIndex -= 1
    11.         PopulateFields()
    12.     End If
    13. End Sub
    14.  
    15. Private Sub nextButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles nextButton.Click
    16.     If currentAuthorIndex = authorList.Count - 1 Then
    17.         MessageBox.Show("No next author")
    18.     Else
    19.         currentAuthorIndex += 1
    20.         PopulateFields()
    21.     End If
    22. End Sub
    23.  
    24. Private Sub lastButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lastButton.Click
    25.     currentAuthorIndex = authorList.Count - 1
    26.     PopulateFields()
    27. End Sub

    Run the application (set AuthorView as the startup object) and ensure that the navigation buttons are working.

    The Update button is easy too. Get the current author and set its values from the textboxes.

    vb Code:
    1. Private Sub update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles update.Click
    2.     Dim currentAuthor As Author = authorList(currentAuthorIndex)
    3.     currentAuthor.FirstName = firstName.Text
    4.     currentAuthor.LastName = lastName.Text
    5. End Sub

    Note that this only modifies an existing author. Nothing has been sent to the database yet. You can do that now; in the click event for the "Send to database" button,

    vb Code:
    1. Private Sub sendToDB_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendToDB.Click
    2.     Dim rowsAffected As Integer
    3.     rowsAffected = publishContext.SaveChanges(True)
    4.     MessageBox.Show(rowsAffected.ToString() + " changes made")
    5.     PopulateFields()
    6. End Sub

    Try it out. Modify an author or authors and see whether your changes make it through to the database. A simple call to publishContext.SaveChanges() works because it still holds a reference to the same objects that were returned from the original ObjectQuery which is in your authorList as well.

    Now, try adding a new author. The "Clear for new author" button should clear the fields to make it obvious (or not) that a new author is being created. The "Save New" button should actually create the Author object.

    vb Code:
    1. Private Sub clearForNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles clearForNew.Click
    2.     firstName.Text = String.Empty
    3.     lastName.Text = String.Empty
    4.     authorIDLabel.Text = "Not yet saved"
    5. End Sub
    6.  
    7. Private Sub createNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles createNew.Click
    8.  
    9.     Dim newAuthor As New Author
    10.     newAuthor.FirstName = firstName.Text
    11.     newAuthor.LastName = lastName.Text
    12.     newAuthor.AuthorID = -1 'To make it obvious that it's new
    13.     authorList.Add(newAuthor)
    14.     publishContext.AddToAuthor(newAuthor)
    15.     currentAuthorIndex = authorList.Count - 1
    16.     PopulateFields()
    17.  
    18. End Sub

    The key here is to use the AddToAuthor method to add the new Author object to your publishContext 'database'. You also are adding it to the list of authors that you are holding.

    Because the list and the publishContext reference the same new Author object, when you add a new author and click "Send to database", you'll notice that the new Author object gets the proper primary key ID instead of the -1 that we placed there. Same principle as before—the new identity is returned and given to the new Author object.

    Next, you will look at the efficiency of the SQL generated behind the scenes for your queries.

  4. #4

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    The Case for Stored Procedures

    The AuthorView form isn't that much different from the PayrollView form, but it does show you that you can deal with the data in different ways, depending on your preference. You did manage to cut down the database calls when navigating through the forms,, which is great. But, the profiler trace shows you queries that aren't exactly satisfactory. This is what I got in the profiler when I updated an author:

    sql Code:
    1. exec sp_executesql N'update [dbo].[Author]
    2. set [FirstName] = @0, [LastName] = @1
    3. where ([AuthorID] = @2)
    4. ',N'@0 nvarchar(6),@1 nvarchar(7),@2
    5. int',@0=N'Lerroy',@1=N'Jenkins',@2=2

    If you've done a lot of enterprise development, you will probably be tearing the last few strands of your remaining hair follicles out right now. Dynamic SQL, that's just not acceptable. In fact, if you were to perform a lot of 'joining' (in a LINQ-to-SQL style) with your objects, you will see some extremely large and convoluted SELECT statements being run against the database in SQL Profiler. If you use an ObjectQuery, you can use its .ToTraceString() method to see the SQL statement that will be used. Go back to the AuthorView form and use a MessageBox to display the ToTraceString of the ObjectQuery:

    vb Code:
    1. Dim authorQuery As ObjectQuery(Of Author) = publishContext.Author.Where("it.FirstName <> 'Mark'")
    2. authorList = authorQuery.ToList()
    3. MessageBox.Show(authorQuery.ToTraceString())
    4. PopulateFields()

    But the query in this specific example isn't that bad:

    Code:
    SELECT [Extent1].[AuthorID] AS [AuthorID],
    [Extent1].[FirstName] AS [FirstName], [Extent1].
    [LastName] AS [LastName]FROM [dbo].[Author] AS
    [Extent1]WHERE [Extent1].[FirstName] <>
    'Mark'
    To illustrate this point further (and show you another query method), go back to the AuthorView form and add another label. You will use this label to display the number of articles that this author has written. For this purpose, you will use an ObjectQuery method called Include. What is the Include method? You have seen that query methods will only retrieve what you ask; for instance, in your current query

    vb Code:
    1. Dim authorQuery As ObjectQuery(Of Author) = publishContext.Author.Where("it.FirstName <> 'Mark'")

    you won't have any information about the author's payroll or articles. You only have information about authors not named Mark. If you look at authorList in a quickwatch window after it has been populated, you will see that the Payroll and Article properties of each Author object have no values. The Include method will therefore load the entities associated with the author object, those that you ask for. Go back to the AuthorView form's load event, and modify the ObjectQuery like this to use the Include method.

    vb Code:
    1. Dim authorQuery As ObjectQuery(Of Author) = publishContext.Author.Where("it.FirstName <> 'Mark'").Include("Article")

    This means get all the authors, except Mark, and for each author, include their associated Article entities. In the PopulateField() method, you now can read the article count.

    vb Code:
    1. articleCountLabel.Text = currentAuthor.Article.Count.ToString()

    Run the form and you should see the articles count label change for each author. But, did you notice the SQL trace string?

    Code:
    SELECT
    [Project1].[AuthorID] AS [AuthorID],
    [Project1].[FirstName] AS [FirstName],
    [Project1].[LastName] AS [LastName],
    [Project1].[C1] AS [C1],
    [Project1].[C3] AS [C2],
    [Project1].[C2] AS [C3],
    [Project1].[ArticleID] AS [ArticleID],
    [Project1].[Title] AS [Title],
    [Project1].[Body] AS [Body],
    [Project1].[AuthorID1] AS [AuthorID1]
    FROM ( SELECT
       [Extent1].[AuthorID] AS [AuthorID],
       [Extent1].[FirstName] AS [FirstName],
       [Extent1].[LastName] AS [LastName],
       1 AS [C1],
       [Extent2].[ArticleID] AS [ArticleID],
       [Extent2].[Title] AS [Title],
       [Extent2].[Body] AS [Body],
       [Extent2].[AuthorID] AS [AuthorID1],
       CASE WHEN ([Extent2].[ArticleID] IS NULL)
          THEN CAST(NULL AS int) ELSE 1 END AS [C2],
       CASE WHEN ([Extent2].[ArticleID] IS NULL)
          THEN CAST(NULL AS int) ELSE 1 END AS [C3]
       FROM  [dbo].[Author] AS [Extent1]
       LEFT OUTER JOIN [dbo].[Article] AS [Extent2]
          ON [Extent1].[AuthorID] = [Extent2].[AuthorID]
       WHERE [Extent1].[FirstName] <> 'Mark'
    )  AS [Project1]
    ORDER BY [Project1].[AuthorID] ASC, [Project1].[C3] ASC
    In case you're shaking your head and are about to give in to the temptation of criticizing large, faceless corporations for poor standards, you must keep in mind that in any given system, ease-of-use and the generic-ness is inversely proportional to the efficiency. So, to make it more convenient to query and load objects, there is a slight hit with your SQL statements.

    However, this is where the ADO.NET Entity Framework shines through; you can tell it to use your own stored procedures instead of the generated SELECT, UPDATE, DELETE, and INSERT statements. Because stored procedures are generally more efficient than dynamic SQL and because you are given this flexibility with the Entity Framework, this is where the real 'power' of the framework is apparent.

    Next, you will map stored procedures with the ADO.NET Entity Framework.

  5. #5

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Using Stored Procedures with the ADO.NET Entity Framework

    Any proper enterprise environment will have a DBA or a set of DBAs who guard and watch over their databases in the same way that a mother bear watches over her cub. If you inappropriately step between the DBAs and the DBOs, you will get mauled. This means that even with the ADO.NET Entity Framework, they will still want to retain ownership of the database and the objects in it. The ADO.NET Entity Framework allows you to use most of the application code as you did before, but with stored procedures that you or they may have written in the most 'optimal' way.

    It'll take a bit of work to get this set up and running, but the effort pays off in the end. You are going to work on using stored procedures with the Article entities on a new form, first starting with a few tasks that you're already familiar with, and then get on to the good stuff.

    1. Creating the SELECT stored procedure(s)
    2. Layout of the ArticleView form
    3. Importing the stored procedure
    4. Using the stored procedure to get entities in our code
    5. Another stored procedure, and using it
    6. Navigation and update code
    7. Ta-daa!


    Obviously, the first step is to create the SELECT stored procedure.
    sql Code:
    1. CREATE PROCEDURE GetArticle
    2.    @ArticleID INT
    3. AS
    4. BEGIN
    5.    SET NOCOUNT ON;
    6.    SELECT ArticleID, Title, Body, AuthorID
    7.    FROM Article
    8.    WHERE ArticleID = @ArticleID
    9. END
    10. GO

    Next, you need to import this newly created stored procedure into your EDM. There are two ways to do this: You can regenerate the EDM and import it via the designer, or you can go directly into the XML and edit it there. You will cover the visual method in this tutorial.

    1. Right-click anywhere in the Entity Designer view and click "Update Model from Database".
    2. Choose Tables and Stored procedures from the dialog box and click Finish.
    3. Next, open the Model Browser tab and search for the newly created stored procedure, GetArticle.
    4. Right-click on it and choose "Create Function Import".
    5. Set the return type as the Article Entities.






    Stored procedures within the EDM are imported as functions, and a function that you import always returns a collection of entities. In future releases, this may change to allow a stored procedure to return a single entity. The result of a stored procedure goes into an ObjectResult<>, similar to how publishContext.Author's return type was ObjectQuery<>.

    To see it working, quickly create an ArticleView form. Add a new form to the solution, ArticleView, with these controls.



    A little simple for now, but you'll expand it as you go along. In the code,

    Top of the class:

    vb Code:
    1. Dim publishContext As New PublishingCompanyEntities
    2. Dim articleLIst As List(Of Article)

    In the form's load event:

    vb Code:
    1. Private Sub ArticleView_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.     Dim articleQuery As ObjectResult(Of Article) = publishContext.GetArticle(1)
    3.     currentArticle = articleQuery.ToList().First()
    4.     PopulateFields()
    5. End Sub

    And your old friend:

    vb Code:
    1. Private Sub PopulateFields()
    2.     If (currentArticle.ArticleID > 0) Then
    3.         currentArticle.AuthorReference.Load()
    4.     End If
    5.  
    6.     articleIDLabel.Text = currentArticle.ArticleID.ToString()
    7.     titleText.Text = currentArticle.Title
    8.     bodyText.Text = currentArticle.Body
    9. End Sub

    This time, you will notice that you make an explicit call to the GetArticle stored procedure, passing it the ArticleID 1. Run the form and you'll see the first article loaded up. And, it's done using your GetArticle stored procedure. This is good because it means that you can optimize complicated queries if you need to and use stored procedures to help you.

    However, in this particular case, when you introduce navigation buttons to the ArticleView form, you'll have to make a new stored procedure call for each button click event (for each ID). Avoid that situation and get all of the Articles in one go instead. Create a GetArticles (plural) stored procedure now.

    sql Code:
    1. CREATE PROCEDURE GetArticles
    2. AS
    3. BEGIN
    4.    SET NOCOUNT ON;
    5.    SELECT ArticleID, Title, Body, AuthorID
    6.    FROM Article
    7. END
    8. GO

    Import the GetArticles function as shown earlier. You then can use an ObjectResult<Article>, convert it ToList(), and assign it to a List<> object.

    Top of the class:

    vb Code:
    1. Dim publishContext As New PublishingCompanyEntities
    2. Dim articleLIst As List(Of Article)
    3. Dim currentArticleIndex As Integer

    Modify the Form Load event now:

    vb Code:
    1. Dim articleQuery As IEnumerable(Of Article) = From ar In publishContext.GetArticles() _
    2.                                               Select ar
    3. articleLIst = articleQuery.ToList()
    4. PopulateFields()

    I used a LINQ-to-Entities query instead of a method expression, hoping you would notice the flexibility available to you. You can introduce your filters into the expression and it won't affect the SP call. To illustrate, just as a test:

    vb Code:
    1. Dim articleQuery As IEnumerable(Of Article) = From ar In publishContext.GetArticles() _
    2.                                               Where ar.ArticleID > 5 _
    3.                                               Select ar

    This will perform a GetArticles SP call and then filter the values returned afterwards. However, you're not interested in filtering it right now, so remove the where clause from the LINQ expression.

    Again, there is a PopulateFields method in this form that changes slightly.


    vb Code:
    1. Private Sub PopulateFields()
    2.     Dim currentArticle As Article = articleLIst(currentArticleIndex)
    3.     If (currentArticle.ArticleID > 0) Then
    4.         currentArticle.AuthorReference.Load()
    5.     End If
    6.  
    7.     articleIDLabel.Text = currentArticle.ArticleID.ToString()
    8.     titleText.Text = currentArticle.Title
    9.     bodyText.Text = currentArticle.Body
    10. End Sub

    Run the form and make sure that the first article still shows.

    Now, go back to the form designer and add the navigation buttons. Also, add an "Update" button. a "Clear for new" button. an "Add as new article" button. and a "Delete" button. Same principles as before — you navigate through the List<> for the navigation buttons, update an object's properties in the List<> for the Update button, clear the fields for the "Clear for new" button, and add a new object to the publishContext for "Add as new article".



    Based on work done in the past few pages, you must have an idea of what the various buttons will do now, so I'll simply list the code for the buttons here, and then you can get down to the main point of this task—using stored procedures for INSERT, UPDATE, and DELETE.

    vb Code:
    1. Private Sub firstButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles firstButton.Click
    2.     currentArticleIndex = 0
    3.     PopulateFields()
    4. End Sub
    5.  
    6. Private Sub previousButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles previousButton.Click
    7.     If currentArticleIndex > 0 Then
    8.         currentArticleIndex -= 1
    9.         PopulateFields()
    10.     Else
    11.         MessageBox.Show("No more articles to display")
    12.     End If
    13. End Sub
    14.  
    15. Private Sub nextButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles nextButton.Click
    16.     If currentArticleIndex = articleLIst.Count - 1 Then
    17.         MessageBox.Show("No more articles to display")
    18.     Else
    19.         currentArticleIndex += 1
    20.         PopulateFields()
    21.     End If
    22. End Sub
    23.  
    24. Private Sub lastButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lastButton.Click
    25.     currentArticleIndex = articleLIst.Count - 1
    26.     PopulateFields()
    27. End Sub
    28.  
    29. Private Sub updateButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles updateButton.Click
    30.    
    31.     Dim currentArticle As Article = articleLIst(currentArticleIndex)
    32.     currentArticle.Title = titleText.Text
    33.     currentArticle.Body = bodyText.Text
    34. End Sub
    35.  
    36. Private Sub clearForNewButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles clearForNewButton.Click
    37.     articleIDLabel.Text = "-1"
    38.     titleText.Text = String.Empty
    39.     bodyText.Text = String.Empty
    40. End Sub
    41.  
    42. Private Sub saveAsNew_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles saveAsNew.Click
    43.  
    44.     Dim newArticle As New Article
    45.     newArticle.Title = titleText.Text
    46.     newArticle.Body = bodyText.Text
    47.     newArticle.ArticleID = -1
    48.     publishContext.AddToArticle(newArticle)
    49.     articleLIst.Add(newArticle)
    50.     currentArticleIndex = articleLIst.Count - 1
    51.     PopulateFields()
    52.  
    53. End Sub
    54.  
    55. Private Sub deleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles deleteButton.Click
    56.  
    57.     Dim currentArticle As Article = articleLIst(currentArticleIndex)
    58.     publishContext.DeleteObject(currentArticle)
    59.     articleLIst.Remove(currentArticle)
    60.     currentArticleIndex = 0
    61.     PopulateFields()
    62.  
    63. End Sub
    64.  
    65. Private Sub submitToDatabase_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitToDatabase.Click
    66.     publishContext.SaveChanges()
    67.     PopulateFields()
    68. End Sub

    Note that although the code looks just like it did in the AuthorView form, when you do map your stored procedures, you won't have to change any of the code.

    Next, you can (finally!) map the INSERT, UPDATE, and DELETE stored procedures.

  6. #6

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Mapping INSERT, UPDATE, and DELETE to Stored Procedures

    Now that the form and basic code has been set up, it would be a good idea to actually have the long-awaited stored procedures ready:

    Insert:

    sql Code:
    1. CREATE PROCEDURE AddNewArticle
    2. @Title NVARCHAR(50),
    3. @Body NVARCHAR(400),
    4. @AuthorID INT = NULL
    5. AS
    6. BEGIN
    7. SET NOCOUNT ON;
    8. INSERT INTO Article(Title, Body, AuthorID)
    9. VALUES(@Title, @Body, @AuthorID)
    10.  
    11. SELECT SCOPE_IDENTITY() AS NewArticleID
    12. END
    13. GO

    For the INSERT stored procedure, it is imperative that you also get the identity of the row inserted.

    Update:

    sql Code:
    1. CREATE PROCEDURE UpdateArticle
    2. @ArticleID INT,
    3. @Title NVARCHAR(50),
    4. @Body NVARCHAR(400),
    5. @AuthorID INT
    6. AS
    7. BEGIN
    8.    SET NOCOUNT ON;
    9. UPDATE Article
    10. SET
    11. Title = @Title,
    12. Body = @Body,
    13. AuthorID = @AuthorID
    14. WHERE
    15. ArticleID = @ArticleID
    16. END
    17. GO
    Delete:

    sql Code:
    1. CREATE PROCEDURE DeleteArticle
    2. @ArticleID INT,
    3. @AuthorID INT = NULL
    4. AS
    5. BEGIN
    6. SET NOCOUNT ON;
    7. DELETE FROM Article WHERE ArticleID = @ArticleID
    8. END
    9. GO

    Finally, to replace the generated SQL with these stored procedures, open Solution Explorer and double-click on the .edmx file that you generated at the beginning of the tutorial.

    Right-click on the Article entity and choose "Stored procedure mapping".



    You will now see the Mapping Details window. It is here that you can choose the stored procedures to map.



    Select "AddNewArticle" for the Insert function as shown, and it will populate the stored procedure parameters for you along with the corresponding Article class properties as it has derived them. Note the direction of the arrows as well, indicating value 'flow'.

    Because you have kept your property names and parameter names the same, it was easy for the EDM designer to match them. However, the "Result Column Bindings" section is empty. This is what the Entity Framework uses to populate the ArticleID property in your new Article objects. You are returning a "NewArticleID" in our AddNewArticle stored procedure, so fill this in here. When you press Enter, it will automatically fill in 'ArticleID' and you'll also notice that the direction of the green arrow in the middle changes, indicating that the result of your SCOPE_IDENTITY() at the end of the stored procedure will be assigned to the ArticleID property in your code. Also, the AuthorID field is empty. Use the dropdown in the Property column for AuthorID to select Author.AuthorID. You should end up with something like this.



    For the Update function, select the UpdateArticle stored procedure. It maps all the fields automatically for you; the only change you want to make is to check the "Use Original Value" checkbox for the ArticleID row. You'll also see that no field maps to the AuthorID field. You will need to use the dropdown in the property column to specifically choose Author.AuthorID.



    Finally, set the DeleteArticle stored procedure as the function for Delete, also manually setting the AuthorID. You should have a stored procedure mapping section that now looks like this.



    The Delete function may appear a little strange to you, because it doesn't make much sense to give it the AuthorID, but you need to pass any foreign key associations to the stored procedure in order to get it to work.

    The good news is that you're all set! Build your solution and run it. Attempt adding a new article, updating one, and deleting one. Finally, click the "Submit changes to the database" button.

    If you run a profiler trace as you do this, you should see nothing but stored procedure calls.

  7. #7

    Thread Starter
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,173

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    The Wordy Bit

    The diligent reader may have noticed that we skipped certain things:

    1. The AuthorView form has no way of deleting an author. Because the author has associations with other tables, you'd need to ensure that a deleted author deletes everything else. This is now left as an exercise to you. It's simply a matter of creating a DeleteAuthor stored procedure and mapping it to the Author entity. This task will also show you a quirk of the framework—you cannot map the Delete function on its own. You must create stored procedures for Insert, Update, and Delete and map them all together.
    2. The ArticleView form has no way of actually associating an author with an article. You may want to change the author of the article or set the author as nobody or just simply look at who the author is. This could be accomplished in three ways.
      1. As shown earlier, using a method expression: publishContext.Article.Include("Author");
      2. For each article entity, perform a currentArticle.AuthorReference.Load(). This will perform a SELECT against the database. This, too, is left as an exercise to you.
      3. Have a stored procedure return all the details for the article and the corresponding author and map it to an Article entity and Author entity. This is a topic in the ADO.NET Entity Framework known as Complex Types, which you shall explore in another tutorial.


    Now that you've seen the code and gone through basic ADO.NET Entity Framework operations, I can get into the digressive harangue. I can already see your fingers hovering over the Ctrl and F4 buttons, but I would strongly recommend having a quick read through this to get a better understanding of the framework for future work and how you could use it in your application(s).
    More Information about the Entity Framework

    There are a few topics that you have already touched upon in this tutorial; you will go into more detail for each of these:

    1. What is the ADO.NET Entity Framework?
    2. How is it different from LINQ to SQL?
    3. Querying data with LINQ to Entity expressions and Method Expressions
    4. Complex Types and Association Sets


    What is the ADO.NET Entity Framework?

    The Entity Framework is Microsoft's first Object-Relational Mapping (ORM) framework for the .NET Framework. An ORM framework allows developers to work with a conceptual schema of a database. A conceptual schema is quite simply the logical representation of objects in a database. In other words, it is a representation of a set of concepts (Forum Members, Threads, Posts) and relationships (one to one, many to one).

    For instance, in your database, if you have a 'link' table that allows for a many-to-many mapping between two other tables, the 'link' table is not an entity in the EDM. It is simply a relationship, but the two main tables that it is linking may be entities. Further, you may have a table that has been horizontally split for some reason; the two tables together map to a single entity.

    When using the framework, you can refer to a Customer entity's Address property (Customer1.Address.PostCode), with the Address actually coming from some other table.

    The Entity Framework abstracts the groundwork required to map the application classes to each other by generating and understanding the relationships between each of them (among other things) so that you do not need to perform database-plumbing in your code. You simply work with the objects in a relational model and remain 'unaware' of the underlying database implementation.

    How Is It Different from LINQ to SQL?

    A commonly asked question.

    • LINQ to SQL was created with rapid application development (RAD) in mind. The Entity Framework was created with enterprise development in mind.
    • LINQ to SQL works with the objects in a database. The Entity Framework works with the conceptual model of a database. As explained earlier, these are two different things. This further means that the Entity Framework allows you to perform queries against relationships between entities, mapping single entities to multiple tables, and so on.
    • LINQ to SQL has the ability to call stored procedures, but not map them the results. The Entity Framework is all about mapping results to entities.
    • Guess which one works with something besides SQL Server?


    Querying Data with LINQ to Entity expressions and Method Expressions

    Throughout the tutorial, you saw a spattering of LINQ to Entities expressions and Query Builder methods or Method Expressions. These are the basic expressions used to query the entities in the EDM. Internally, both of them evaluate to the same thing, so using one over the other is a matter of preference.

    For example, this query method:

    vb Code:
    1. Dim articleQuery As ObjectQuery(Of Article) = publishContext.Article.Where("it.ArticleID > 5")

    can be represented as

    vb Code:
    1. Dim articleQuery As IQueryable(Of Article) = From ar in publishContext.Article _
    2.                                                             Where ar.articleId > 5 _
    3.                                                             Select ar

    Although LINQ to Entities may be more familiar to you, take a short look at query methods. Query methods allow you to parametrize the queries going through. Taking the above example, you therefore can do this:

    vb Code:
    1. Dim articleQuery As ObjectQuery(Of Article) = publishContext.Article.Where("it.ArticleID > @SomeArticleID", new ObjectParameter("SomeArticleID", 5))

    Going back to one of the forms you worked on—the PayrollView—you could have modified a query slightly to load the author's first name and last name together using the Select method.

    vb Code:
    1. 'Uses "ADO.NET Entity SQL Expressions" or "method based queries"
    2. authorList.DataSource = publishContext.Author.Select("it.FirstName + ' ' + it.LastName As FullName, it.AuthorID")
    3. authorList.DisplayMember = "FullName"
    4. authorList.ValueMember = "AuthorID"

    Other more commonly used methods are OrderBy, GroupBy, and Where. For more information on these methods, visit the Query Builder Methods page on MSDN.

    Complex Types and Association Sets

    One of the scenarios described earlier in this tutorial potentially called for the use of a ComplexType. You could have created a CAuthor type, and assigned it as a property of a CArticle type, which would have enabled you to work with them more efficiently for your purposes. Or, to look at it another way, think of a Person entity that has the properties PhoneCountryCode, PhoneAreaCode, PhoneNumber, PhoneExtension. Using a ComplexType, you could group those fields into a single Phone entity. Read more about Complex Type Objects.

    Association Sets allow you to use and refer to entities as properties of other entities in the Entity Framework. Because the EDM generated will not always have the association that you want there, you will sometimes need to define your own association sets between entities and also use stored procedures to perform INSERTs or DELETEs across them.

    Conclusion

    This has been a quick look at the ADO.NET Entity Framework. So far, you have seen how to perform a few basic operations of the ADO.NET Entity Framework.

    • LINQ to Entities to retrieve data
    • Method expressions to retrieve data
    • SaveChanges()
    • Stored procedures to retrieve data
    • Stored procedures to add, update, and delete data.


    Even though there is a lot more to the Entity Framework, what you have learned here can serve as a basis for future application design. A lot of us are (subconsciously) familiar with ORM but have not used it to its full potential, so you may find yourself finding your steps initially as you wrap your head around a slightly different concept of creating data-driven applications.


    Hopefully, this tutorial was useful to you in some way. Feel free to post in the VB.NET/Database Development/C# forum if you have any further questions about this.



    Keywords
    ADO.NET
    Entity Framework
    EF
    mendhak
    introduction
    tutorial
    VB.NET
    C#

  8. #8
    Hyperactive Member
    Join Date
    May 2006
    Posts
    426

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Thanks for tut and the Links.
    Last edited by maps; Nov 22nd, 2008 at 07:03 AM. Reason: Resolved Problem

  9. #9
    New Member
    Join Date
    Jan 2009
    Posts
    1

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Great article. Coming from vb6 I keep missing the imports that are required to make these things work.

    Imports System.Data.Objects
    Imports System.Data.Objects.DataClasses

  10. #10
    Hyperactive Member
    Join Date
    Nov 2005
    Posts
    259

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Does anybody have this in a printable version? I tried to print it out but I couldn't get the code sections to wrap.

  11. #11
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,344

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Quote Originally Posted by FastEddie View Post
    Does anybody have this in a printable version? I tried to print it out but I couldn't get the code sections to wrap.
    Try the archived version of the thread.
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    https://get.cryptobrowser.site/30/4111672

  12. #12
    New Member
    Join Date
    Nov 2009
    Location
    Oldbury West Midlands UK
    Posts
    9

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Hi Mendhak,
    I'm new to the forum and new to Entity Framework, therefore hoping to learn from your tutorial. I am using Visial Basic Express 2010 with a standard installation so I only have the Sql Server Compact 3.5. Will there be any way to get round the use of Stored Procedures and or Views if I proceed with the tutorial?

    Kenkob

  13. #13
    Hyperactive Member
    Join Date
    Dec 2009
    Location
    sydney
    Posts
    265

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Hi All,

    i followed the tutorial step by step as this is my first EF attempt
    i get an error on the second line, see attached screen shot.
    Name:  error.png
Views: 21892
Size:  90.7 KB

    Code:
        Dim query As IQueryable(Of CUSTOMERS) = From C In ABMcontext.CUSTOMERS Where C.UniqueID = cboCustomers.SelectedValue Select C
                Dim selectedCus As List(Of CUSTOMERS) = query.ToList
                cus = selectedCus.First()
    i cant see what i'm doing wrong

  14. #14
    New Member
    Join Date
    Mar 2014
    Posts
    7

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Everything went well up to the point of coding datasource and DisplayMember for the combo box to display the author names (cboAuthor in my case). Code runs but list not populated. At first it was forcing me to write
    cboAuthor.DataSource = publishContext.Authors (whereas you had publishContext.Author)

    Re-did the wizard and deselected Pluralization option, but that didn't help.

  15. #15
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,532

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Set the .ValueMember first, then the .DisplayMember property, THEN set the .DataSource... actually, it doesn't matter if you set .Display or .Value member first, but set them both before the .DataSource... it has to do with how the list renders when it gets the data... by default it will use the .ToString method, if there is one... when there isn't, that's when you get a blank list.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  16. #16
    New Member
    Join Date
    Mar 2014
    Posts
    7

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Thanks for the suggestion, techgnome, but list is still blank.
    Here is my code:
    Public Class PayrollView

    Dim publishContext As New PublishingCompanyEntities1
    Dim currentPayroll As New Payroll

    Private Sub PayrollView_Load(sender As Object, e As EventArgs) Handles Me.Load
    cboAuthor.ValueMember = "FirstName"
    cboAuthor.DisplayMember = "FirstName"
    cboAuthor.DataSource = publishContext.Author
    End Sub

    Also, for a beginner like myself, where do I start reading? I've worked with VBA in Access. Now that I'm moving to Visual Studio and Microsoft SQL I hardly know where to begin. The textbooks I have are already obsolete as far as Visual Studio 2013 is concerned..code samples in the book don't work. There's got to be a more systematic way to approach this thing than losing days at a time hung up on simple things like trying to get a combo box to work. There's my little rant for the day. :-)

    (What I really WANT to say is AAAAAAARRRGGGHH!) There, that felt good.

  17. #17
    New Member
    Join Date
    Mar 2014
    Posts
    7

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Also should mention:
    I can't import System.Data.EntityClient namespace. (Does not pop up as an option in Intellisense)

    Why not, and how do I fix?

    Thanks!

  18. #18
    Lively Member
    Join Date
    Dec 2011
    Posts
    66

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    i've started with the basic lesson, except i have an error "the configuration element is not declared"

    i've just insert the entity data model and the code until the names were inserted into the combobox. (by running the program it shows nothing).

    i asume there something wrong with the app.config but what?



    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </configSections>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <connectionStrings>
    <add name="PublishingCompanyEntities" connectionString="metadata=res://*/PublishingCompany.csdl|res://*/PublishingCompany.ssdl|res://*/PublishingCompany.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DELAPLACE_BVBA\SQLEXPRESS;initial catalog=PublishingCompany;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    </connectionStrings>
    <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    </entityFramework>
    </configuration>

  19. #19
    Junior Member
    Join Date
    Apr 2009
    Posts
    31

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    A quick query before I start (no pun intended)
    I am writing an app that will be used on a network with multiple machines reading & writing to a single database on the server.
    If I declare a single public Entity on each machine e.g. Public HRDBContext As New HRDBEntities (my database is called HRDB)...
    Will that entity be dynamic, will it reflect any changes made to the database by other users, or am I going to have to declare it privately every time a form is loaded or a control needs filling etc
    Same for the entities e.g. Public _xContact As New Contact (Contacts being a table in the DB)
    I was thinking I could declare all of the entities etc in a class or module and reference them from any form etc
    Thanks in advance.
    Last edited by Aussie; Apr 5th, 2017 at 05:04 PM. Reason: incomplete question

  20. #20
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,532

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    It will get the data that is in the database at the time you execute the get ... if after you get the data, if someone adds more records, you won't see it until another get is performed.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  21. #21
    Junior Member
    Join Date
    Apr 2009
    Posts
    31

    Re: Tutorial: An Introduction to the ADO.NET Entity Framework

    Ok thanks techgnome. I figured as much but thought I'd check to be sure.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width