在实体框架中表示连接表 [英] Representing a Junction Table in Entity Framework

查看:51
本文介绍了在实体框架中表示连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a schema where the following logic applies:

  • 字符串可以属于多个位置.
  • 多个位置可以具有多个 String ,或者没有 String .
  • 必须记录形成 Location String 之间的关系的 DateTime (作为 DateScraped )
  • A String can belong to multiple locations.
  • Multiple Locations can have multiple String, or no String.
  • The DateTime (As DateScraped) at which the relationship between Location and String was formed must be recorded.

基本上,我已使用连接表将关系映射为多对多关系:

Basically, I've mapped the relationship as a many-to-many relationship using a junction table like so:

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

In mapping the chart in Code First EF6 (Using SQLite), I have the following objects:

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中的实现不同吗?

I've based what I've done so far on conjecture as I cannot seem to find any concrete information on how a relationship such as this must be built. Normally I'd use a junction table, but that is in vanilla SQL. Is the implementation different in EF?

我是否必须手动管理 LocationStringMapping 表,还是我不知道某种隐式关系模型?

Am I going to have to cumbersomely manage the LocationStringMapping table by hand or is there some kind of implicit relationship model I don't know about?

推荐答案

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

这篇关于在实体框架中表示连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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