如何在将父级保存到EF时排除子对象?

时间:2015-04-10 00:20:27

标签: c# entity-framework

我的父母给我的孩子有一个可以为空的外键:

public class Company
{
    public int? AddressID {get;set;}
    public Address Address {get;set;}
}

public class Address
{
    public string StreetAddress {get;set;} //not nullable in DB
}

当我尝试保存到数据库时,EF尝试保存Address对象,尽管它为null:

var company = new Company{AddressID = null } //other stuff is populated that matters

try
{
    _context.Entry(company).State = EntityState.Added;
    _context.SaveChanges();
}
catch (Exception exception)
{
    //Throws Validation error because StreetAddress is not nullable
}

我试过这些

{
    _context.Entry(company).State = EntityState.Detached;
    _context.Company.Add(company);
}

{
    _context.Companies.Add(company);
}

它们都需要填充街道地址。

如何在保存时忽略可以为空的孩子?

1 个答案:

答案 0 :(得分:0)

我预感子外键是不可为空的。尝试将属性设置为虚拟:

public virtual Address Address { get; set; }