简体   繁体   中英

Preventing cyclic Parent/Child data when using Entity Framework Core

Given a data model which contains reference to its parent (adjacency list):

class Foo
{
   public int Id { get; set; }
   virtual Foo Parent { get; set; }
}

How can I guarantee that no cyclic references will be committed to the database?

ok:

a
  b
    c

NOT ok:

a
  b
    c
      a

Is this something I can do by setting the isolation level (to Serializable)? Is this best done using some sort of trigger in the database itself? Should I be using a different model for my hierarchical data?

If I understand your problem correctly, I think it is enough to put the following in the "Parent" class:

    [JsonIgnore] //if you will ever Serialize it
    [ForeignKey("OrderProductionNumber")] //using System.ComponentModel.DataAnnotations.Schema;
    public virtual Foo Parent { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM