2

Lets assume I have a class model like so:

public class BlogPost
{
     ...

     [Key]
     public Guid Id {get;private set;}
     public virtual ICollection Comments {get;private set;}
}
public class Comment
{    
     [Key]
     public Guid Id {get;private set;}
     public string Text{get;set;}
}

Don't read too much into my pseudocode here, but what I want to know if: Do the comment class have to have a Guid BlogPostId or BlogPost parent property?

can I model the comment class as I did above, and still have it mapped to the blogpost through the BlogPost.Comments property. e.g. by providing some other mapping attributes

I don't want aggregate members to know anything about their AR.

1 Answer 1

2

Yes, you are not forced to specify post id (i.e. FK) or reference in comment entity when post have navigation property for comments:

public class BlogPost
{
    public Guid Id { get; private set; }
    public virtual ICollection<Comment> Comments { get; private set; }
}

public class Comment
{
    public Guid Id { get; private set; }
    public string Text { get; set; }
}

In this case EF will generate FK column in Comments table which will have name BlogPost_Id (by default it uses parent entity name with parent entity key property name). Also you don't need to mark key column with [Key] attribute if column has name like id or TypeNameId.

Generated tables will look like:

enter image description here

If you want to change generate FK name without declaring property on comment entity, you can use fluent mappings (generally I suggest you to use fluent mappings instead of data annotation attributes - that will make your entities cleaner). To provide mappings override OnModelCreating method of your data context:

modelBuilder.Entity<BlogPost>()
    .HasMany(bp => bp.Comments)
    .WithRequired()
    .Map(c => c.MapKey("PostId"))
    .WillCascadeOnDelete();
Sign up to request clarification or add additional context in comments.

2 Comments

Oohh , nice, didn't think it was smart enough to do this by convention only. thanks :)
Is it possible to name the column for the foreign key w/o adding a property for it? e.g. if I want the foreign key to map to an existing column for legacy reasons?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.