[英]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? 我可能认为这完全错了,可以解释为什么我在谷歌上找不到答案但是,你能先在EF代码中找到一对(零或多)关系吗?
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. Item1
可以有多个或零Item2
,并且在添加到数据库时不需要任何Item2
。 Item1
is deleted then it cascades to any anything in Item2List
. 如果删除了Item1
,则它会级联到Item2List
任何内容。 Item2
requires 1 Item1
. Item2
需要1个Item1
。 Item2
is deleted then it does not affect Item1
. 如果删除了Item2
,则它不会影响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? 再次,这可能是我的误解但是.ForeignKey("dbo.Item1", t => t.Item1Id, cascadeDelete: true)
意味着当你删除Item2
删除Item1
也是如此? or have I got this wrong and does this mean, when Item1
is deleted then delete Item2
? 或者我错了,这是否意味着,当Item1
被删除然后删除Item2
?
you can done this using fluent api like this 你可以使用流畅的api这样做
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 但您需要编辑外键以允许这样的null
public int? Item1Id{get;set;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.