在实体框架中表示连接表 [英] Representing a Junction Table in Entity Framework
问题描述
我正在创建一种适用于以下逻辑的架构:
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 multipleString
, or noString
. - The
DateTime
(AsDateScraped
) at which the relationship betweenLocation
andString
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屋!