【问题标题】:Code First Object not properly instantiating代码优先对象未正确实例化
【发布时间】:2011-10-13 20:19:49
【问题描述】:

我有一个从 activeentity 继承的班级部门

public class ActiveEntity : Entity, IActive
    {
        public ActiveEntity()
        {
            IsActive = true;
        }
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public Guid Id { get; set; }
        public bool IsActive { get; set; }
        [Timestamp, ScaffoldColumn(false), DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Computed)]
        public Byte[] Timestamp { get; set; }
        [ScaffoldColumn(false)]
        public string CreationUserId { get; set; }
        [ScaffoldColumn(false)]
        public string LastModifiedUserId { get; set; }
    }
    public class Department:ActiveEntity    
    {
        public Department()
        {
            this.Address = new DepartmentAddress();
        }
        [StringLength(9),MinLength(9),MaxLength(9)]
        public string Name { get; set; }

        public Guid ManagerId { get; set; }
        [UIHint("AjaxDropdown")]
        public User Manager { get; set; }
        public Guid? AddressId { get; set; }
        public DepartmentAddress Address { get; set; }

        public ICollection<OverheadRate> OverheadRates { get; set; }


    }

我只是使用注释没有 Fluent API。数据保存到数据 Sql Server 2008 就好了,但是地址对象永远不会被实例化,即使我有上下文使用包含

return c.Set<Department>().Include(d => d.Address).Include(d => d.Manager).Where(predicate);

返回数据我运行 sql profiler 然后运行查询它返回正确的数据。

有什么想法或建议吗?

【问题讨论】:

    标签: entity-framework-4.1 ef-code-first


    【解决方案1】:

    删除在 Department 构造函数中实例化地址 (this.Address = new DepartmentAddress();)。在默认构造函数中实例化导航引用是邪恶的,并且有如下讨厌的副作用:

    What would cause the Entity Framework to save an unloaded (but lazy loadable) reference over existing data?

    EF 4.1 Code First: Why is EF not setting this navigation property?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多