Question

I'm making my first steps with Fluent Api and I'm trying to understand how to do the following: This is my model.

public class Person
{
    public int Id {get ; set;}
    public List<View> Viewers {get; set;}
}

public class View
{
    public int Id {get; set;}
    public Person Viewer {get; set;}
}

This is a simplification of my model, I want to keep track of Person's that access some others profiles. I want to know for every person who has seen their profile.

I have tried this:

var view = modelBuilder.Entity<View>();
        view.HasKey(v=>v.Id);

var person = modelBuilder.Entity<Person>();
        person.HasKey(r => r.Id);
        person.HasMany(t => t.Viewers).WithRequired(t=>t.Viewer);

I know this seems super silly, but from my code I want to be able to navigate:

Person -> Viewers (let's take viewer 1) -> Viewers, and so on...

Is this the right approach?

Thanks in advanced!

Was it helpful?

Solution

try this

public class Person
{   [Key]
    public int Id { get; set; }
    public ICollection<View> Viewers { get; set; }
}

public class View
{   [Key]
    public int Id { get; set; }
    public int ViewerId { get; set; } //this is a ForeingKey
    public Person Viewer { get; set; }
}

public class MyDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<View> Views { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<View>().HasRequired(a => a.Viewer).WithMany().HasForeignKey(a => a.ViewerId);
        base.OnModelCreating(modelBuilder);
    }
}

you may do the same with DataAnnotation Attributes and then it does't need to use Fluent API.

public class View
{
    public int Id { get; set; }
    public int ViewerId { get; set; }
    [ForeignKey("ViewerId")] // here is a foreignkey property
    [InverseProperty("Viewers")] // here is a navigation property in Person class
    public Person Viewer { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top