How to work with collections

前端 未结 3 2032
你的背包
你的背包 2020-12-08 23:55

Can anyone write mini-guide which explains how to work with collections in EF?

For example I have following models:

public class BlogPost
{
    publ         


        
3条回答
  •  暖寄归人
    2020-12-09 00:22

    It seems that Commentsnavigation property does not works properly. Try to provide to BlogPost model the actual referencig field to PostComment table. Also rename the navigation property in PostComments for the EF naming compliance.

    public class BlogPost
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime DateTime { get; set; }
    
        public int PosCommentId {get; set; }
        public List PostComments { get; set; }
    }
    

    If this neither works you have to define manually your relationship, but before help in this, you'd better provide the schema of this two tables in your db.

    UPDATE 01:

    First tip: You are using singular named tables. This is not compliant to EF naming convention. Pluralization has to be turned off. Just put this line in OnModelCreating method.

    modelBuilder.Conventions.Remove();
    

    Second tip: My previous advice was totally wrong do not consider it anymore, just use your old models schema. Now, assuming a one-to-many relationship between comment and post:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        modelBuilder.Conventions.Remove();
        modelBuilder.Entity().HasRequired(c => c.ParentPost)
                .WithMany(p => p.Comments);
    
        base.OnModelCreating(builder);
    
    }
    

    For more INFOs :

    EF one-to-many relationship tutorial

    Relationship and navigation properties

    Configuring Relationships with the Fluent API

提交回复
热议问题