简体   繁体   中英

EF Code-First User Testimonial System

I have a User entity in my DbContext . What I want is that users should be able to give references/leave comments for each other , therefore I have created Reference entity.

public class Reference
{
    public virtual User By { get; set; } // user who leaves a reference

    public virtual User To { get; set; } // user who has given a reference

    public string Opinions { get; set; }
}

in User entity

public virtual ICollection<Reference> ReferencedTo { get; set; } // collection of references that user has given

public virtual ICollection<Reference> ReferencedBy { get; set; } // collection of references that user has been given

What should I do to make it work with either DataAnnonations or FluentAPI, or how would you approach to this and solve?

You need to do something like this:

public class Reference
{
    public int ReferenceId { get; set; }

    public int ByUserId { get; set; }

    public virtual User By { get; set; } // user who leaves a reference

    public int ToUserId { get; set; }

    public virtual User To { get; set; } // user who has given a reference

    public string Opinions { get; set; }
}

public class User
{
    public int UserId { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Reference> ReferencedTo { get; set; } // collection of references that user has given

    public virtual ICollection<Reference> ReferencedBy { get; set; } // collection of references that user has been given
}

public class MyContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Reference> References { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Reference>()
            .HasRequired(x => x.By)
            .WithMany(x => x.ReferencedBy)
            .HasForeignKey(x => x.ByUserId)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Reference>()
            .HasRequired(x => x.To)
            .WithMany(x => x.ReferencedTo)
            .HasForeignKey(x => x.ToUserId)
            .WillCascadeOnDelete(false);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM