1

因为这个问题我很沮丧,你不知道...

我有 2 个课程:PostComment。我使用 EF 4 POCO 支持,我的 .edmx 模型中没有外键列(评论类没有PostID 属性,但Post 属性)

class Comment {
    public Post post { get; set; }
    // ...
}

class Post {
    public virtual ICollection<Comment> Comments { get; set; }
    // ...
}

有人能告诉我为什么下面的代码不起作用吗?我想为帖子创建一个新评论:

Comment comm = context.CreateObject<Comment>();
Post post = context.Posts.Where(p => p.Slug == "something").SingleOrDefault();
// post != null, so don't worry, be happy

// here I set all other comm properties and...
comm.Post = post;

context.AddObject("Comments", comm);        // Exception here
context.SaveChanges();

例外是:

无法将值 NULL 插入列“PostID”、表“Blog.Comments”;列不允许空值。插入失败。

...这个“PostID”列当然是 Posts 表的外键。

任何帮助将不胜感激!

4

1 回答 1

1

好的,经过很长时间我终于弄明白了。

我使用了 Entity Framework Feature CTP 3 中的纯代码方法,而不是 .edmx 文件。这是对我有帮助的文本的链接:

http://blogs.msdn.com/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx

于 2010-03-28T17:07:23.713 回答