How do I load a row from the database using the Entity Framework? RRS feed

  • Question

  • I ran the entity framework and it created a couple of classes (actually several classes) like this:

    namespace EFTest { using System; using System.Collections.Generic; public partial class SalesRepresentative { public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } public string CellPhone { get; set; } } }

    public partial class SalesEntities : DbContext
        public SalesEntities()
                : base("name=SalesEntities")
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
            throw new UnintentionalCodeFirstException();
        public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
        public DbSet<Sales_Regions> Sales_Regions { get; set; }
        public DbSet<SalesRegion> SalesRegions { get; set; }
        public DbSet<State> States { get; set; }
        public DbSet<Territory_Descriptions> Territory_Descriptions { get; set; }

    And I found an example of using them like this:

    SalesRepresentative sr;
    using (var ef = new SalesEntities())
        sr = new SalesRepresentative() { ID = IDin };

    But the tutorial did not mention anything about loading a record.  I looked all over the place here but could not find anything.  Can someone point me to a tutorial that explains how to read rows or give me a code snippet?


    • Moved by DotNet Wang Monday, August 29, 2016 6:08 AM EF related
    Thursday, August 25, 2016 9:16 PM

All replies

  • Hello MarDude,

    I understand getting started can be hard.  The nice thing about EF is it takes away a lot of the plumbing so you should be able to access the objects directly off of you context (or ef in your example).  In other words ef.SalesRepresentatives.First(rep => rep.ID = 1);

    Here are some posts that will hopefully help:

    This targets MVC but illustrates how to use EF:


    • Proposed as answer by DotNet Wang Monday, August 29, 2016 6:07 AM
    Friday, August 26, 2016 1:54 AM
  • Thanks, just what I needed!!
    Friday, August 26, 2016 1:13 PM
  • Hi MarDude,

    Could you please mark it as answer if the reply is helpful to you.

    It will be very beneficial for other community members who have the similar questions. 

    Best regards,

    Cole Wu

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, September 2, 2016 3:22 AM