EF5代码优先级联删除上 [英] EF5 Code First Cascade on delete
本文介绍了EF5代码优先级联删除上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有什么办法让删除的级联发生时,我删除计算机?基本上当我删除,我希望它删除实例,除了环境和产品的所有引用计算机
计算机实体:
公共类电脑
{
[关键]
公众诠释标识{搞定;组; }
公共字符串Ip地址{搞定;组; }
公共字符串名称{;组; }
公共字符串UserFriendlyName {搞定;组; }
公共字符串描述{搞定;组; }
}
实例实体:
公共类实例
{
公共实例()
{
TestResults =新的HashSet< TestResult中>();
环境=新的HashSet<环境与GT;();
}
[关键]
公众诠释标识{搞定;组; }
公共字符串名称{;组; }
公共字符串版本{搞定;组; }
公共字符串UserFriendlyName {搞定;组; }
公共虚拟产品产品{搞定;组; }
公共虚拟档案LastKnownProfile {搞定;组; }
公共虚拟计算机计算机{搞定;组; }
公共虚拟的ICollection<&的TestResult GT; TestResults {搞定;组; }
公共虚拟的ICollection<环境与GT;环境{搞定;组; }
}
解决方案
您需要定义用流利的API关系。使用这样的:
保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
{
modelBuilder.Entity<电脑>()
.HasRequired(X => x.Instance)
.WithRequiredPrincipal(X => x.Computer)
.WillCascadeOnDelete();
modelBuilder.Entity<&实例GT;()
.HasRequired(X => x.LastKnownProfile)
.WithRequiredPrincipal(X => x.Instance)
.WillCascadeOnDelete();
modelBuilder.Entity<&实例GT;()
.HasMany(X => x.TestResults)
.WithOptional(X => x.Instance)
.WillCascadeOnDelete();
}
这是记录相当不错的MSDN:的用流利的API 配置关系
Is there any way to Get a cascade on delete to happen when I remove a computer? Basically when I delete a computer I want it to remove the instance and all its references except Environments and Product.
Computer Entity:
public class Computer
{
[Key]
public int Id { get; set; }
public string IpAddress { get; set; }
public string Name { get; set; }
public string UserFriendlyName { get; set; }
public string Description { get; set; }
}
Instance Entity:
public class Instance
{
public Instance()
{
TestResults = new HashSet<TestResult>();
Environments = new HashSet<Environment>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public string UserFriendlyName { get; set; }
public virtual Product Product { get; set; }
public virtual Profile LastKnownProfile { get; set; }
public virtual Computer Computer { get; set; }
public virtual ICollection<TestResult> TestResults { get; set; }
public virtual ICollection<Environment> Environments { get; set; }
}
解决方案
You need to define the relationships using the Fluent API. Use something like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Computer>()
.HasRequired(x => x.Instance)
.WithRequiredPrincipal(x => x.Computer)
.WillCascadeOnDelete();
modelBuilder.Entity<Instance>()
.HasRequired(x => x.LastKnownProfile)
.WithRequiredPrincipal(x => x.Instance)
.WillCascadeOnDelete();
modelBuilder.Entity<Instance>()
.HasMany(x => x.TestResults)
.WithOptional(x => x.Instance)
.WillCascadeOnDelete();
}
This is documented pretty well on MSDN: Configuring Relationships with the Fluent API
这篇关于EF5代码优先级联删除上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文