C# 删除CascadeOnDelete的公约
在特殊情况下,我试图从外键关系中删除一些CascadeOnDelete标记 这种情况是,如果关系的一端是特定类型,而另一端不是,那么我想将cascadeOnDelete设置为falseC# 删除CascadeOnDelete的公约,c#,entity-framework-6,entity-framework-migrations,C#,Entity Framework 6,Entity Framework Migrations,在特殊情况下,我试图从外键关系中删除一些CascadeOnDelete标记 这种情况是,如果关系的一端是特定类型,而另一端不是,那么我想将cascadeOnDelete设置为false class CascadeOnDeleteSuppressionConvention : IConceptualModelConvention<AssociationType>, IConvention { public void Apply(AssociationType association
class CascadeOnDeleteSuppressionConvention : IConceptualModelConvention<AssociationType>, IConvention
{
public void Apply(AssociationType associationType, DbModel model)
{
if(!associationType.IsForeignKey)
return;
if(associationType.AssociationEndMembers[0].GetPOCOType() == typeof(someType) &&
associationType.AssociationEndMembers[1].GetPOCOType() != typeof(someTypeOtherType))
associationType.AssociationEndMembers[0].DeleteAction = DeleteAction.None;
}
}
class CascadeOnDeleteSuppressionConvention:IConceptualModelConvention,IConvention
{
公共void应用(AssociationType AssociationType,DbModel模型)
{
如果(!associationType.IsForeignKey)
返回;
if(associationType.AssociationEndMembers[0].GetPOCOType()==typeof(someType)&&
associationType.AssociationEndMembers[1]。GetPOCOType()!=typeof(someTypeOtherType))
associationType.AssociationEndMembers[0]。DeleteAction=DeleteAction.None;
}
}
不幸的是,我不知道如何从代码优先模型中获取POCO类型。有人能提供如何获取该类型的信息吗?我找到了一个解决方案,可以从概念模型中获取EntityType,从应用程序中获取CLRType
ConceptualModel.EntityTypes
中有元数据,适合我的需要:
public EntityType FindEntityType(DbModel model, Type type)
{
var const metadataPropertyName = "http://schemas.microsoft.com/ado/2013/11/edm/customannotation:ClrType";
var entityType = model.ConceptualModel.EntityTypes.SingleOrDefault(
e => e.MetadataProperties.Contains(metadataPropertyName) &&
e.MetadataProperties.GetValue(metadataPropertyName).Value as Type == type
);
return entityType;
}
截取的代码可用于获取必要的信息并检查EntityType是否匹配
EntityType到ClrType代码
public Type GetClrType(EntityType entityType)
{
const string metadataPropertyName = "http://schemas.microsoft.com/ado/2013/11/edm/customannotation:ClrType";
MetadataProperty metadataProperty;
if (entityType.MetadataProperties.TryGetValue(metadataPropertyName, true, out metadataProperty))
return metadataProperty.Value as Type;
return null;
}