【问题标题】:Representing a Junction Table in Entity Framework在实体框架中表示连接表
【发布时间】:2018-11-03 22:50:46
【问题描述】:

我正在创建一个适用以下逻辑的架构:

  • String 可以属于多个位置。
  • 多个Locations可以有多个String,或者没有 String
  • 必须记录LocationString之间形成关系的DateTime(作为DateScraped)。

基本上,我使用这样的联结表将关系映射为 多对多 关系:

在 Code First EF6(使用 SQLite)中映射图表时,我有以下对象:

public class Location
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long LocationId { get; set; }

    [Required]
    public string Country { get; set; }

    [Required]
    public string CityOrProvince { get; set; }

    [Required]
    public string PlaceOrCity { get; set; }

    [Required]
    public string PostalCode { get; set; }
}

public class String
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long StringId { get; set; }

    [Required]
    public string SearchString { get; set; }
}

public class LocationStringMapping
{
    [Required]
    public string LocationId { get; set; }

    [Required]
    public string StringId { get; set; }

    [Required]
    public DateTime DateScraped { get; set; }
}

到目前为止,我所做的一切都是基于猜想,因为我似乎找不到任何关于必须如何建立这样的关系的具体信息。通常我会使用联结表,但那是在普通 SQL 中。 EF 中的实现是否不同?

我将不得不手动繁琐地管理LocationStringMapping 表,还是有某种我不知道的隐式关系模型?

【问题讨论】:

  • 我认为this article 可能会有所帮助。他们的关键术语是导航属性。另外,this answer 可能会有所帮助。

标签: c# entity-framework ef-code-first many-to-many junction-table


【解决方案1】:
public class Location
{
    public long LocationId {get;set;}
    public virtual ICollection<LocationStringMapping> LocationStringMappings {get;set;}
    //other
}

public class String
{
    public long StringId {get;set;}
    public virtual ICollection<LocationStringMapping> LocationStringMappings {get;set;}
    //other
}

public class LocationStringMapping
{
    [Key, Column(Order = 0)]
    public long LocationId { get; set; }
    [Key, Column(Order = 1)]
    public long StringId { get; set; }

    public virtual Location Location {get;set;}
    public virtual String String {get;set;}

    public DateTime DateScraped {get;set;}
}

【讨论】:

  • 谢谢!我没想到像这样的隐式关系会这么简单,但是在测试您的解决方案后,它按预期工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多