Entity Framework Data Annotations equivalent of .W

2019-02-11 22:06发布

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?

3条回答
闹够了就滚
2楼-- · 2019-02-11 22:47

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

public int? OutputTypeID { get; set; }
查看更多
Emotional °昔
3楼-- · 2019-02-11 22:51

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.

查看更多
The star\"
4楼-- · 2019-02-11 23:09

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.

查看更多
登录 后发表回答