简体   繁体   English

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

[英]How to exclude the child object when saving a parent to EF?

I have a nullable foreign key from my parent to my child: 我有一个从父母到孩子的可以为空的外键:

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
}

When I try and save to the Database EF tries to save the Address object despite it being null: 当我尝试保存到数据库时,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
}

I tried these 我尝试了这些

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

{
    _context.Companies.Add(company);
}

Both of them still require a street address be populated. 他们两个都仍然需要填写街道地址。

How can I ignore the nullable children when saving? 保存时如何忽略可为空的子代?

I have a hunch the child foreign key is non-nullable. 我预感孩子的外键是不能为空的。 Try setting the property to virtual: 尝试将属性设置为虚拟:

public virtual Address Address { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM