NPoco.Много ко многим - PullRequest
0 голосов
/ 25 апреля 2019

У меня есть две таблицы в моей модели db и c #:

public class Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}


public class Customer
{
    public int Id { get; set; }  
    public string FirstName { get; set; }  
    public string LastName { get; set; }
}

Также у меня есть таблица, которая соединяет Address и Customer таблицы со столбцами: Id CustomerId AddressId

Как я могу реализовать отношения «многие ко многим» между таблицами, используя NPoco?

1 Ответ

0 голосов
/ 25 апреля 2019

используйте этот пример:

public class Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public virtual ICollection<CustomerAddress> CustomerAddresses{ get; set; }
}

public class Customer
{
    public int Id { get; set; }  
    public string FirstName { get; set; }  
    public string LastName { get; set; }
    public virtual ICollection<CustomerAddress> CustomerAddresses{ get; set; }
}

public class CustomerAddress
{
    public int CustomerId{ get; set; }
    public int AddressId{ get; set; }

    public virtual Address Address{ get; set; }
    public virtual Customer Customer{ get; set; }
}

и конфигурация при создании модели:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<CustomerAddress>()
       .HasKey(c => new { c.CustomerId, c.AddressId});

   modelBuilder.Entity<Customer>()
       .HasMany(c => c.CustomerAddresses)
       .WithRequired()
       .HasForeignKey(c => c.CustomerId);

   modelBuilder.Entity<Address>()
       .HasMany(c => c.CustomerAddresses)
       .WithRequired()
       .HasForeignKey(c => c.AddressId);  
}
...