从数据库获取行,实体框架

时间:2015-10-12 07:16:59

标签: c# sql database entity-framework

我创建了一个.mdf数据库文件。我创建了一个如下图所示的表格:

Table

我试图使用Entity框架,与数据库通信。

在这里,我使用上下文连接到数据库:

namespace SportsStore.domain.Concrete
{
    //Associate the model with the database
    //This class then automatically defines a property for each table in the database that I want to work with. 
    public class EFDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
    }
}

在这里,我试图从数据库中获取行:

namespace SportsStore.domain.Concrete
{
    public class EFProductRepository : IProductRepository
    {
        private EFDbContext context = new EFDbContext();

        public IEnumerable<Product> Products
        {
            get { return context.Products; }
        }
    }
}

当我运行我的应用程序时,没有打印出任何内容。数据库中的行不会打印出来。

值得注意的是,当我启动我的应用程序时,一个红色箭头显示在SportsStore.mdf上方,如下图所示:

Table

任何可以帮助我的人?我应该在Web.Config上添加一些东西吗?如果是这样,我应该添加什么?

2 个答案:

答案 0 :(得分:0)

看起来你在web.config中的实体框架没有连接,如

  <connectionStrings>
<add name="ManageCustomersEntities" connectionString="metadata=res://*/Entities.Model1.csdl|res://*/Entities.Model1.ssdl|res://*/Entities.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=YOURSERVER;initial catalog=DBNAME;persist security info=True;user id=sa;password=******;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings>

然后为 EFDbContext

设置连接

希望它有所帮助!

答案 1 :(得分:0)

您可以通过Entity Framework获取表格行:

public class BlProduct
{
    public List<Product> Select()
    {
        EFDbContext context = new EFDbContext();
        try
        {
            return (from a in context.Product Select a).ToList();
        }
        catch (Exception)
        {
            return null;
        }
    }
}

打电话给这堂课是公平的。