Entity Framework Data Annotations equivalent of .WillCascadeOnDelete(false);

青春壹個敷衍的年華 提交于 2019-12-09 00:25:44

问题


I'm currently using EF Code First 4.3 with migrations enabled, but automatic migrations disabled.

My question is simple, is there a data annotations equivalent of the model configuration .WillCascadeOnDelete(false)

I would like to decorate my class so that the foreign key relationships do NOT trigger a cascading delete.

Code sample:

public class Container
{
    public int ContainerID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Output> Outputs { get; set; }
}

public class Output
{
    public int ContainerID { get; set; }
    public virtual Container Container { get; set; }

    public int OutputTypeID { get; set; }
    public virtual OutputType OutputType { get; set; }

    public int Quantity { get; set; }
}  

public class OutputType 
{
    public int OutputTypeID { get; set; }
    public string Name { get; set; }
}

I Would like to do something like this:

public class Output
{
    [CascadeOnDelete(false)]   
    public int ContainerID { get; set; }
    public virtual Container Container { get; set; }

    [CascadeOnDelete(false)]    
    public int OutputTypeID { get; set; }
    public virtual OutputType OutputType { get; set; }

    public int Quantity { get; set; }
}  

This way i would be able to scaffold the migration correctly. which scaffolds the foreign key relationships to be cascade deleted at the moment.

Any ideas, other than using Model Configuration?


回答1:


No there is no such equivalent. You must use fluent API to remove cascade delete selectively or you must remove OneToManyCascadeDelete convention to remove it globally.




回答2:


Create a mapping class (the fluent syntax) and use the code below:

// add relationships "Post" and "User" to a "Comment" entity
this.HasRequired(t => t.Post)
    .WithMany(t => t.Comments)
    .HasForeignKey(d => d.PostID)
    .WillCascadeOnDelete(false); // <---

this.HasOptional(t => t.User)
    .WithMany(t => t.Comments)
    .HasForeignKey(d => d.UserID)
    .WillCascadeOnDelete(false); // <---

Here's a nice post on how to set up fluent mappings if you need more info.




回答3:


Just make the FK property nullable can prevent cascade delete from happening:

public int? OutputTypeID { get; set; }


来源:https://stackoverflow.com/questions/10431990/entity-framework-data-annotations-equivalent-of-willcascadeondeletefalse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!