如何使用实体框架从数据库加载行?

问题描述:

我运行了实体框架,它创建了几个类(实际上是几个类),如下所示:

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 };
    ef.SalesRepresentatives.Add(sr);
    ef.SaveChanges();
}

但教程没有提到有关加载记录的任何内容。  我在这里看了整个地方&https://msdn.microsoft.com/en-us/data/ee712907但找不到任何东西。  有人可以指点我的教程解释如何阅读行
或给我一个代码片段吗?

But the tutorial did not mention anything about loading a record.  I looked all over the place here https://msdn.microsoft.com/en-us/data/ee712907 but could not find anything.  Can someone point me to a tutorial that explains how to read rows or give me a code snippet?

谢谢

Hello MarDude,

Hello MarDude,

我知道入门可能很难。  关于EF的好处是它占用了大量的管道,因此您应该能够直接从您的上下文(或者在您的示例中为ef)访问对象。  换句话说,ef.SalesRepresentatives.First(rep
=> rep.ID = 1);

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:

https://msdn.microsoft.com/en-us/data/jj573936.aspx?f=255&MSPPError=-2147217396

https://msdn.microsoft.com/en-us/data/jj573936.aspx?f=255&MSPPError=-2147217396

这是针对MVC但是说明如何使用EF:

This targets MVC but illustrates how to use EF:

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an -entity-framework-data-model-for-an-asp-net-mvc-application

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application