[英]Getting foreign key from RelationshipEndMembers in EF6
我正在尝试使用一些T4模板自动执行一些EF6 linq查询。
我有一个名为Application的主表,它具有许多1- *和一对-关系。
我已经能够弄清楚如何获取简单导航属性的外键表ID值,但是我对多对多关系有疑问。
到目前为止,这是我能够找到的代码。
var association = ((AssociationType)entity.RelationshipType);
if (association.ReferentialConstraints.Count > 0)
{
var fromProperties = association.ReferentialConstraints[0].FromProperties;
var toProperties = association.ReferentialConstraints[0].ToProperties;
#>
//query = query.Where(p => p.<#=toProperties[0].Name#> == idToFind);
<#
}
else if (association.RelationshipEndMembers.Count > 0)
{
var test = (AssociationEndMember)entity.FromEndMember;
// ????????
// Trying to create something like
// query = query.Where(p => p.ManyToManey.ForeignKeyId== idToFind)
// I'm able to find the ManyToMany value but not the foreign Key value
#>
var hellowordl = "True";
<#
所以我最终浏览了edmx属性并搜索表的主键
var allEdmx = typeMapper.GetItemsToGenerate<EntityType>(itemCollection);
// entity is just an entry in allEdmx
var association = ((AssociationType)entity.RelationshipType);
if (association.ReferentialConstraints.Count > 0)
{
var fromProperties = association.ReferentialConstraints[0].FromProperties;
var toProperties = association.ReferentialConstraints[0].ToProperties;
#>
//query = query.Where(p => p.<#=toProperties[0].Name#> == idToFind);
<#
}
else if (association.RelationshipEndMembers.Count > 0)
{
var getPriamryKey = allEdmx.FirstOrDefault(d => d.Name == entity.FromEndMember.Name);
var simpleProperties = typeMapper.GetSimpleProperties(getPriamryKey);
if (simpleProperties.Any())
{
var primaryKeys = typeMapper.GetPrimaryKeys(ef, simpleProperties);
if (primaryKeys.Any() && primaryKeys.Count() == 1)
{
#>
//query = query.Where(p => p.<#=entity.Name#>.<#=codeStringGenerator.JustGetName(primaryKeys.FirstOrDefault())#> == idToFind);
<#
}
}
// Added this to the codeStringGenerator class
public string JustGetName(EdmProperty edmProperty)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0}",
_code.Escape(edmProperty)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.