简体   繁体   中英

EF code first, one to (zero or many)?

I maybe thinking about this completely wrong and could explain why I can't find an answer on google but, can you have a one to (zero or many) relationship in EF code first?

Example

public class Item1
{
     public int Id {get;set;}

     public virtual ICollection<Item2> Item2List {get;set;}
}

public class Item2
{
     public int Id {get;set;}

     public int Item1Id {get;set;}

     public virtual Item1 Item1 {get;set;}
}

So from the above I would like the rules to be this.

  • Item1 can have many or zero Item2 and does not require any when being added to the database.
  • If Item1 is deleted then it cascades to any anything in Item2List .
  • Item2 requires 1 Item1 .
  • If Item2 is deleted then it does not affect Item1 .

EDIT:

Running the above the migration created is this

CreateTable(
            "dbo.Item1",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                })
            .PrimaryKey(t => t.Id);

        CreateTable(
            "dbo.Item2",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Item1Id = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.Item1", t => t.Item1Id, cascadeDelete: true)
            .Index(t => t.Item1Id);

again, this maybe my misunderstanding but does .ForeignKey("dbo.Item1", t => t.Item1Id, cascadeDelete: true) mean when you delete Item2 delete Item1 as well? or have I got this wrong and does this mean, when Item1 is deleted then delete Item2 ?

you can done this using fluent api like this

 modelBuilder.Entity<Item2>()
                .HasOptional<Item1>(s => s.Item1 ) 
                .WithMany(s => s.Item2List).WillCascadeOnDelete(false);

but you need to edit your foreign key to allow null like this

public int? Item1Id{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