Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...