实体框架6如何使用两个外键保存实体

时间:2016-08-18 19:31:21

标签: entity-framework

有实体。页面可以属于Site或PageBlock,但不能同时属于它们。此处还有一个特定的参考:Page->Row->PageBlock->Page->Row->PageBlock...关于保存到数据库的问题。

public class Page {
    public virtual List<Row> Rows { get; set; }
    public virtual int? SiteId { get; set; }
    public virtual int? BlockId { get; set; }
}

public class Row {
    public virtual List<AbstractBuildBlock> BuildBlocks { get; set; }
}

PageBlock

public class PageBlock : AbstractBuildBlock {
    public Page PageContent{ get; set; }
}

如果从page对象Site添加BlockId,则应设置null并设置SiteId,如果来自PageBlock:{{ 1}},BlockId - NOT NULL

在更新SiteId - NULLPage时,我手动设置了外键,因为我知道PageBlock

但是当我添加新的PageId, BlockId时,我不知道它是Id,我依靠EF6来做下一个:

"PageOwnerEntity"

对于此输入

public int Add(Page obj)
    {
        if(obj.Id == 0 || obj.Id >= 10000) //Id >=10000 - object was created at client side
        //but at this moment I don't know what Id will be set to obj after it will be added to db
        {
            context.Pages.Add(obj); //Id auto-increment
        }else
        {
            //here update
        }
    }

我有这个输出

Site { NewPage1 }
PageBlock { NewPage2 }

我需要

Site { Id:1, PageId:1 }
PageBlock {Id:1, PageId:2 } //Interesting that PageId for PageBlock was setted                        
                                             ^
Page1 { Id: 1, SiteId: 1, BlockId: null}     | 
Page2 { Id: 2, SiteId: 1, BlockId: null}//but another end of relationship missed :(

有没有人知道这个问题的解决方案?

1 个答案:

答案 0 :(得分:1)

通常不会从microsoft推荐禁用级联删除,但您可以这样做:

1)禁用整个应用程序的级联删除:

public class MyDbContext : DbContext
{
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
   // Related to your entities with m..n      
   modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

   // Related to your entities with 1..n              
   modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
   ....

2)对于一种关系,在本地禁用级联删除:

modelBuilder.Entity<Page>()
         .HasOptional(c => c.Rows)
         .WithMany()
         .WillCascadeOnDelete(false);

modelBuilder.Entity<Row>()
         .HasOptional(c => c.BuildBlocks)
         .WithMany()
         .WillCascadeOnDelete(false);

你的实体模型对我来说有点奇怪也许你可以更清楚地配置它以避免那些问题。