Entity framework 如何在实体框架代码优先方法中添加具有一对一关联的实体?

Entity framework 如何在实体框架代码优先方法中添加具有一对一关联的实体?,entity-framework,Entity Framework,我首先使用EF4.4+代码 我试图将ChartofAccount实体添加到DBContext,并填充公司的键,但它要求我在验证时也填充公司的CompanyName。我以为DBContext会帮我查找关联公司,而不是尝试添加新公司 public class ChartofAccount: MasterData { public ChartofAccount() { Company = new Company();

我首先使用EF4.4+代码

我试图将ChartofAccount实体添加到DBContext,并填充公司的键,但它要求我在验证时也填充公司的CompanyName。我以为DBContext会帮我查找关联公司,而不是尝试添加新公司

    public class ChartofAccount: MasterData
    {
        public ChartofAccount()
        {
            Company = new Company();
            Category1 = new AccountCatagory();
            Category2 = new AccountCatagory();
        }

        [Key]
        [Required]
        public string Code { get; set; }

        public virtual Company Company { get; set; }

        [Required]
        public string AccountName { get; set; }

        [Required]
        [StringLength(3)]
        public string AccountCurrency { get; set; }

        public virtual AccountCatagory Category1 { get; set; }

        public virtual AccountCatagory Category2 { get; set; }

        public string Reference { get; set; }

        public bool HasTransaction { get; set; }


    }

public class Company : MasterData
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string CompanyName { get; set; }

        [Required]
        DateTime CurrentAccountPeriod { get; set; }

        [Required]
        [StringLength(3)]
        public string BaseCurrencyCode { get; set; }
    }

遗憾的是,仅仅一个相关实体的主键是不够的。您需要往返到数据库以在相同的数据上下文中获取实体

例如:

var Company = db.Company.Single(d => d.ID == id);
ChartofAccountToAdd.Company = Company;
db.ChartofAccount.Add(ChartofAccountToAdd);
db.SubmitChanges();
这将创建与现有公司的关系

编辑:

当我回答时,我完全忘记了这一点。编辑您的
ChartoAccount
模型以包含
公司的外键,如:

    public class ChartofAccount: MasterData
    {

        {rest of your model}

        public int CompanyID { get; set; }

    }

然后将外键设置为新的
int
属性。实体框架将创建没有任何问题的关系。不要对模型上的
Company
属性设置任何内容。

确实很遗憾。我可以用fluentapi自动化这个过程吗?我不这么认为。Fluent API用于定义数据库结构而不是自动执行数据库任务。@BryanFok我完全忘记了在模型上手动创建外键,然后以这种方式设置ID。不需要往返数据库。谢谢Steven。我知道[ForeignKey]的方法,但我不喜欢这样。