Question

I'm trying to insert rows using entity framework. I used code first. I have document and author entities,

public class Document
{
    [Key]
    public int DocumentId { get; set; }
    public string Title { get; set; }
    public string PublicationName { get; set; }
    public List<Author> Authors { get; set; } 
}


public class Author
{
    [Key]
    public int AuthorId { get; set; }
    public string name { get; set; }
    public string surname { get; set; }
    public List<Document> Documents { get; set; }
}

I wanted to add an author to a document object. I can add a document with auhtors;

   Document d=new Document();
   d.Authors.Add(a);

Then I save the context with db.SaveChanges() it can add document and its authors but I don't want it to add a new author when there is an existing one. I check this if there is no author like I look for, create a new one by a new author instance. Problem here is, ef adds one more even there is an existing author record. I don't want this if so it should get the existing authors id and add.

Is this many to many usage right? If I only add author to document authors list, is it ok?

Was it helpful?

Solution 2

Not sure what you want exactly since you did not post your author creation. But see if this helps

Author author =context.Authors.SingleOrDefault(o=>o.AuthorId ==authorId);

if(author ==null)
{
 author = new Author ();
 //set properties
 context.Authors.Add(author);
}

Document d=new Document();
d.Authors.Add(a);

OTHER TIPS

You should use Add for adding new entity and Attach for attaching existing ones. Here's good reference explaining this:

http://msdn.microsoft.com/en-us/data/jj592676.aspx

First Attach your Author to context and then add it to d.Authors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top