【发布时间】:2011-05-26 14:16:34
【问题描述】:
当使用实体框架代码优先库的 CTP 5(如 here 宣布的那样)时,我正在尝试创建一个映射到一个非常简单的层次结构表的类。
这是构建表的 SQL:
CREATE TABLE [dbo].[People]
(
Id uniqueidentifier not null primary key rowguidcol,
Name nvarchar(50) not null,
Parent uniqueidentifier null
)
ALTER TABLE [dbo].[People]
ADD CONSTRAINT [ParentOfPerson]
FOREIGN KEY (Parent)
REFERENCES People (Id)
这是我希望自动映射回该表的代码:
class Person
{
public Guid Id { get; set; }
public String Name { get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
class FamilyContext : DbContext
{
public DbSet<Person> People { get; set; }
}
我在 app.config 文件中设置了连接字符串:
<configuration>
<connectionStrings>
<add name="FamilyContext" connectionString="server=(local); database=CodeFirstTrial; trusted_connection=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
最后我尝试使用该类来添加父实体和子实体,如下所示:
static void Main(string[] args)
{
using (FamilyContext context = new FamilyContext())
{
var fred = new Person
{
Id = Guid.NewGuid(),
Name = "Fred"
};
var pebbles = new Person
{
Id = Guid.NewGuid(),
Name = "Pebbles",
Parent = fred
};
context.People.Add(fred);
var rowCount = context.SaveChanges();
Console.WriteLine("rows added: {0}", rowCount);
var population = from p in context.People select new { p.Name };
foreach (var person in population)
Console.WriteLine(person);
}
}
这里显然缺少一些东西。我得到的例外是:
列名“PersonId”无效。
我了解约定优于配置的价值,我和我的团队对摆脱 edmx / 设计师噩梦的前景感到兴奋 --- 但似乎没有关于约定是什么的明确文档。 (对于单数类名,我们只是幸运地使用了复数表名的概念)
对于如何使这个非常简单的示例落实到位的一些指导,我们将不胜感激。
更新:
将 People 表中的列名从 Parent 更改为 PersonId 允许添加 fred 继续进行。但是,您会注意到 pebbles 已添加到 fred 的 Children 集合中,因此我希望在添加 Fred 时也会将鹅卵石添加到数据库中,但事实并非如此。这是一个非常简单的模型,所以我有点沮丧,因为在将几行输入数据库时应该涉及这么多的猜测工作。
【问题讨论】:
标签: entity-framework code-first