与代码优先实体框架的单向多对多关系 [英] unidirectional many-to-many relationship with Code First Entity Framework

查看:83
本文介绍了与代码优先实体框架的单向多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是EF的新手,并尝试使用代码优先方法获得多对多单向关系.例如,如果我有以下两个类(不是我的真实模型),它们之间具有N * N关系,但在客户"方面没有导航属性.

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

此语法迫使我必须为客户"实体使用"WithMany". 以下 url 表示按照惯例,Code First总是将单向关系解释为一对多."

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?

推荐答案

使用此:

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

并将其映射为:

modelBuilder.Entity<User>()
    .HasMany(r => r.TaggedCustomers)
    .WithMany() // No navigation property here
    .Map(m =>
        {
            m.MapLeftKey("UserId");
            m.MapRightKey("CustomerId");
            m.ToTable("BridgeTableForCustomerAndUser");
        });

这篇关于与代码优先实体框架的单向多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆