gpt4 book ai didi

c# - 删除时的 EF5 Code First 级联

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:51 25 4
gpt4 key购买 nike

有没有什么方法可以在我删除计算机时让删除发生级联?基本上,当我删除一台计算机时,我希望它删除实例及其除环境和产品之外的所有引用。

计算机实体:

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

实例实体:

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

最佳答案

您需要使用 Fluent API 定义关系。使用这样的东西:

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

这在 MSDN 上有很好的记录:Configuring Relationships with the Fluent API

关于c# - 删除时的 EF5 Code First 级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14774444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com