views:

300

answers:

1

Hi all, I'm so frustrated because of this problem, you have no idea...

I have 2 classes: Post and Comment. I use EF 4 POCO support, I don't have foreign key columns in my .edmx model (Comment class doesn't have PostID property, but has Post property)

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

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

Can someone tell me why the code below doesn't work? I want to create a new comment for a post:

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();

The Exception is:

Cannot insert the value NULL into column 'PostID', table 'Blog.Comments'; column does not allow nulls. INSERT fails.

... this 'PostID' column is of course a foreign key to the Posts table.

Any help will be appreciated!

A: 

OK, after a long time I've finally figured it out.

I used Code Only approach from Entity Framework Feature CTP 3 instead of .edmx file. Here is a link to the text which helped me:

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

Darmak