EntityFramework按ID或字段获取相关项目

时间:2012-03-09 02:51:29

标签: entity-framework

我有两个对象,如:

public class Area : IEntity
    {
        public virtual int Id { get; set; }
        public virtual int AreaTypeLookupId { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(100)]
        public virtual string Name { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(2)]
        public virtual string VMRegionCode { get; set; }
        public virtual int GISPrimaryKeyId { get; set; }
        public virtual string ConcatenatedGISAreaIds { get; set; }
        public virtual int? ParentAreaId { get; set; }
        public virtual int? ParentRegionAreaId { get; set; }
        [Column(TypeName = "char")]
        [StringLength(3)]
        public virtual string CostCenterCode { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(64)]
        public string CreatedByUserName { get; set; }
        public DateTime CreatedDateTime { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(64)]
        public string LastModifiedByUserName { get; set; }
        public DateTime? LastModifiedDateTime { get; set; }

        // Navigation properties
        public virtual AreaTypeLookup AreaTypeLookup { get; set; }
    }

public class AreaTypeLookup : IEntity
    {
        [Column("Id")]
        public virtual int AreaTypeLookupId { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(100)]
        public virtual string Name { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(10)]
        public virtual string ShortName { get; set; }
        public virtual int? AreaTypeLevelLookupId { get; set; }
        public virtual int? OperationTypeLookupId { get; set; }
        public virtual int? ParentAreaTypeLookupId { get; set; }
        public bool IsAvailableToSetBudgetAgainst { get; set; }
        public int DisplaySortOrder { get; set; }
        public bool IsProtected { get; set; }
        public DateTime? DeletedDateTime { get; set; }
        public int? ManagedByServiceTypeLookupId { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(64)]
        public string CreatedByUserName { get; set; }
        public DateTime CreatedDateTime { get; set; }
        [Column(TypeName = "varchar")]
        [StringLength(64)]
        public string LastModifiedByUserName { get; set; }
        public DateTime? LastModifiedDateTime { get; set; }
    }

我想要的是获取areatypelookupid = 3的所有区域。对于此区域类型,名称为“region”

获得代码可维护性的最佳方法是什么:

此:

var areas = _unitOfWork.AreaRepository.GetAll().Where(x => x.AreaTypeLookupId == 3);

或者这个:

var areas = _unitOfWork.AreaRepository.GetAll().Where(x => x.AreaTypeLookup.Name == "region");

我认为“region”应该真正来自资源文件。

1 个答案:

答案 0 :(得分:0)

通常,您需要使用主键,因为它应该是不可变的。但是,如果您可以保证查找名称不会更改,则按名称搜索是可以容忍的。我说可以忍受的原因是因为除了不变性之外,从主键运行查询在数据库上会更有效率。