-1

I have class Plant with some attributes.

public class Plant
{
    public int Id { get; set; }

    // some attributes

    [Display(Name = "Благоприятные соседи")]
    public virtual List<Plant> PositivePlants { get; set; }

    [Display(Name = "Нежелательные соседи")]
    public virtual List<Plant> NegativePlants { get; set; }

    public Plant()
    {
        PositivePlants = new List<Plant>();
        NegativePlants = new List<Plant>();
    }
}

I hope that EF will create 3 tables in database:

Plants:
   Id int PK;
   // some another attributes

NegativePlants:
   Plant_Id int PK FK;
   Negative_Id int PK FK;

PositivePlants:
   Plant_Id int PK FK;
   Positive_Id int PK FK;enter code here

But by default I get another schema. How I can get following schema using DataAnnotation attributes or Fluent Api?

amofialka
  • 25
  • 7
  • To set a DB schema in the fluent API it's `modelBuilder.HasDefaultSchema("schema");` and in annotations it's `[Table("Plant", Schema="schema")]`. But you could have found that by searching in less time that it would take to write the question, is that really what you're after? – stuartd Nov 15 '17 at 12:14
  • I have not any schema in database. I am developing my project using Code First approach. I am interesting how define my class Plant (using DA or Fluent Api) that I can get schema I wrote above. – amofialka Nov 15 '17 at 12:24
  • Ah OK. I suggest you edit your question to show the schema that is generated. – stuartd Nov 15 '17 at 12:36

1 Answers1

0

I solved this. I overrided OnModelCreating method of DBContext in a context class like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Plant>()
            .HasMany(p => p.ReversedPositivePlants)
            .WithMany(p => p.PositivePlants)
            .Map(m => m.ToTable("PositivePlants").MapLeftKey("Plant_Id").MapRightKey("Positive_Id"));

        modelBuilder.Entity<Plant>()
            .HasMany(p => p.ReversedNegativePlants)
            .WithMany(p => p.NegativePlants)
            .Map(m => m.ToTable("NegativePlants").MapLeftKey("Plant_Id").MapRightKey("Negative_Id"));

        base.OnModelCreating(modelBuilder);
    }
amofialka
  • 25
  • 7