实体框架 - 使用外键删除对象,保留父对象

时间:2014-04-04 09:15:29

标签: c# entity-framework ef-code-first

我有以下型号:

public class Company
{
    //Primary key
    public string ID { get; set; } 

    //Foreign key
    public int? LogotypeID { get; set; }
}

public class Logotype
{
    //Primary key
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int? ID { get; set; }

    //Foreign key
    public string CompanyID { get; set; }
}

如何从公司表中删除标识,不用删除公司行?

使用:
http://msdn.microsoft.com/en-us/library/system.data.entity.dbset.remove(v=vs.113).aspx DbSet.Remove(Logotype)抛出以下异常:

{"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Companies_dbo.Logotypes_LogotypeID\". The conflict occurred in database \"ShipReg\", table \"dbo.Companies\", column 'LogotypeID'.\r\nThe statement has been terminated."}

有什么想法吗?

BR, 添

1 个答案:

答案 0 :(得分:2)

在公司中添加虚拟财产,例如

public class Company
{
    //Primary key
    public string ID { get; set; } 

    //Foreign key
    public int? LogotypeID { get; set; }

    public virtual Logotype Logotype {get;set;}
}

然后

dbContext.Entry<Company>(company).State=EntityState.Modified;
dbContext.Entry<Logotype>(company.Logotype).State=EntityState.Deleted;