Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unidirectional many-to-many relationship with Code First Entity Framework

I am new to EF, and trying to get many-to-many unidirectional relationship with code first approach. For example, if I have following two classes (not my real model) with be a N * N relationship between them, but no navigation property from "Customer" side.

public class User {
   public int UserId { get; set; }
   public string Email { get; set; }
   public ICollection TaggedCustomers { get; set; }
}
public class Customer {
  public int CustomerId { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

The mapping code looks like ...

modelBuilder.Entity()
        .HasMany(r => r.TaggedCustomers)
        .WithMany(c => c.ANavgiationPropertyWhichIDontWant)
        .Map(m =>
        {
            m.MapLeftKey("UserId");
                m.MapRightKey("CustomerId");
                m.ToTable("BridgeTableForCustomerAndUser");
        });

This syntax force me to have "WithMany" for "Customer" entity. The following url, says "By convention, Code First always interprets a unidirectional relationship as one-to-many."

Is it possible to override it, or should I use any other approach?

like image 773
Ajay Bhosale Avatar asked Nov 15 '11 12:11

Ajay Bhosale


People also ask

How does Entity Framework handle many-to-many relationships in core?

Many-to-many relationships require a collection navigation property on both sides. They will be discovered by convention like other types of relationships. The way this relationship is implemented in the database is by a join table that contains foreign keys to both Post and Tag .

What is the difference between ICollection and list?

Solution 2. ICollection<T> is an interface, List<T> is a class.

What is OnModelCreating in Entity Framework?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.


1 Answers

Use this:

public class User {
    public int UserId { get; set; }
    public string Email { get; set; }
    // You must use generic collection
    public virtual ICollection<Customer> TaggedCustomers { get; set; }
}

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

And map it with:

modelBuilder.Entity<User>()
    .HasMany(r => r.TaggedCustomers)
    .WithMany() // No navigation property here
    .Map(m =>
        {
            m.MapLeftKey("UserId");
            m.MapRightKey("CustomerId");
            m.ToTable("BridgeTableForCustomerAndUser");
        });
like image 76
Ladislav Mrnka Avatar answered Oct 11 '22 09:10

Ladislav Mrnka