我在表用户中有 1 个用户。我只是想查询该表中的所有记录。我想填充列表变量。
数据库:TestTF
表:用户 UserId int IdentityField UserName nvarchar(64)
应用程序配置
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="TestEF" connectionString="Data Source=.;Initial Catalog=TestEF;Integrated Security=True" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
TestEFContext.cs(正在使用的上下文)
public class TestEFContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserConfig());
}
}
用户配置文件
public class UserConfig : EntityTypeConfiguration<User>
{
public UserConfig()
{
HasKey(x => x.UserId);
}
}
用户.cs
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
WinForm 中的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TestEFContext ctx = new TestEFContext();
List<User> list = (from d in ctx.Users
select d).Take(5).ToList();
foreach (User user in list)
Debug.WriteLine(user.UserName);
this.comboBox1.DisplayMember = "UserName";
this.comboBox1.DataSource = list;
}