c# - 在 Entity Framework 中表示联结表

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

我正在创建一个应用以下逻辑的模式:

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

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

sqldbm

在映射 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 表,或者是否存在某种我不知道的隐式关系模型?

最佳答案

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

关于c# - 在 Entity Framework 中表示联结表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513929/

相关文章:

c# - 将 TransactionScope 与 System.Data.OracleClient 结合使用 - TransactionAbortedException

c# - 我怎么知道什么时候到达数据读取器的末端?

c# - 不更新数据库

entity-framework - EntityFramework 给出 IDisposable 错误

c# - 使用 UWP 通过拖放重新排序可绑定(bind) ListView

c# - 如何等待有条件的任务?

entity-framework - NHibernate 中的 Lazy 是什么意思

c# - 无法将类型 A 转换为类型 B。LINQ to Entities 仅支持转换 EDM 原语或枚举类型

asp.net-mvc-3 - EF 4.1 Code First 多重多对多关系

c# - 由于默认值约束,Code First 迁移失败