Q1.如何为我的数据库中的单列表手动创建一个极其简单的 Entity Framework 模型,并对其进行查询?
表格如下所示:
CREATE TABLE dbo.MyTable (
Value int NOT NULL CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED
);
我有一个 POCO 可以映射到它:
public class MyTable {
public int Value { get; set; }
}
Q2. 那么,如何查询MyTable
呢?用Expression<Func<MyTable, bool>>
lambda 将决定返回哪些行并将投影到 SQL 中?
我是 EF 的新手,但不是 C# 或软件开发的新手。我问这个问题是因为现在我只想在 LINQPad 中快速证明某些东西的概念,而不使用 EF 实体数据模型向导,这样将来很容易编写出这样的代码。
最佳答案
您只需要在下面的代码中,即可粘贴到 LinqPad
class MyTable
{
public int Value { get; set; }
}
class MyTableConfiguration : EntityTypeConfiguration<MyTable>
{
public MyTableConfiguration()
{
ToTable("dbo.MyTable");
HasKey(x => x.Value);
Property(x => x.Value).HasColumnName("Value").IsRequired();
}
}
class MyDbContext : DbContext
{
public IDbSet<MyTable> MyTableSet { get; set; }
public MyDbContext(string connectionString) : base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new MyTableConfiguration());
}
}
void Main()
{
MyDbContext context = new MyDbContext("Data Source=(local);Initial Catalog=SO33426289;Integrated Security=True;");
Expression<Func<MyTable, bool>> expr = x => x.Value == 42;
context.MyTableSet.Where(expr).Dump();
}
您需要确保引用 EntityFramework
NuGet 包和 System.ComponentModel.Annotations.dll
。以下是我使用的命名空间:
System.ComponentModel.DataAnnotations.Schema
System.Data.Entity
System.Data.Entity.ModelConfiguration
System.Data.Entity.ModelConfiguration.Configuration
关于c# - 在 Entity Framework 中手动为单个表创建模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426289/