加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Fluent api Cascade删除与一个表的关系

发布时间:2020-12-15 21:03:28 所属栏目:百科 来源:网络整理
导读:我有以下配置.我有一个用户.用户有邮政地址和物理地址(见下文). public class UserProfile{ public Guid UserProfileId {get; set;} public Guid PostalAddressId {get;set;} public virtual Address PostalAddress {get;set;} public Guid PhysicalAddressI
我有以下配置.我有一个用户.用户有邮政地址和物理地址(见下文).

public class UserProfile
{
    public Guid UserProfileId {get; set;}

    public Guid PostalAddressId {get;set;}
    public virtual Address PostalAddress {get;set;}

    public Guid PhysicalAddressId {get;set;}
    public virtual Address PhysicalAddress {get;set;}
}

public class Address{
    public Guid AddressId {get;set;}
    public string LineOne {get;set;}
    public string LineTwo {get;set;}
    public string LineThree {get;set;}
}

接下来是我流畅的映射

public UserProfileMapping()
{
    ToTable("UserProfile");
    HasKey(pk => pk.UserProfileId);
    Property(pr => pr.UserProfileId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

    HasRequired(a => a.PostalAddress).WithMany().HasForeignKey(fk => fk.PostalAddressId);
    HasRequired(a => a.PhysicalAddress).WithMany().HasForeignKey(fk => fk.PhysicalAddressId);
}

public AddressMapping()
{
    ToTable("Address");
    HasKey(pk => pk.AddressId);
    Property(pr => pr.AddressId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}

当我尝试运行update-database时,我得到:

Introducing FOREIGN KEY constraint
‘FK_dbo.UserProfile_dbo.Address_PhysicalAddressId’ on table
‘UserProfile’ may cause cycles or multiple cascade paths. Specify ON
DELETE NO ACTION or ON UPDATE NO ACTION,or modify other FOREIGN KEY
constraints.

我需要在Address对象上没有任何反向映射.
我还需要能够硬删除UserProfile对象,包括其子地址(其中只有两个地址表).

我的问题是,我想要的是什么?如果是这样,我做错了什么?

[编辑]
Address对象也用于UserCompany和Customer等对象.

解决方法

因为地址不是UserProfile的子节点,而只是关联,所以您不想使用级联删除:

HasRequired(a => a.PostalAdress)
    .WithMany()
    .HasForeignKey(fk => fk.PostalAddressId)
    .WillCascadeDelete(false);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读