EntityTypeConfiguration如何获取key属性?

时间:2014-01-13 06:47:10

标签: c# .net asp.net-mvc-4 entity-framework-5

我正在使用c#,EF 5和MVC4 我正在使用EntityTypeConfiguration来设置主键和后端表

  public class AuditZoneMap : EntityTypeConfiguration<AuditZone>
    {
        public AuditZoneMap()
        {
            // Primary Key
            HasKey(t => t.Id);


            // Properties
            Property(t => t.Description)
                .HasMaxLength(100);


            // Table & Column Mappings
            ToTable("AuditZone");
            Property(t => t.Id).HasColumnName("Id");
            Property(t => t.Description).HasColumnName("Description");
            Property(t => t.Valid).HasColumnName("Valid");          
            Property(t => t.CreatedDate).HasColumnName("CreatedDate");
            Property(t => t.CreatedBy).HasColumnName("CreatedBy");
            Property(t => t.ModifiedDate).HasColumnName("ModifiedDate");
            Property(t => t.ModifiedBy).HasColumnName("ModifiedBy");

            // Relationships        
            HasOptional(t => t.CreatedByUser)
               .WithMany(t => t.CreatedByAuditZone)
               .HasForeignKey(d => d.CreatedBy);

            HasOptional(t => t.ModifiedByUser)
                .WithMany(t => t.ModifiedByAuditZone)
                .HasForeignKey(d => d.ModifiedBy);


        }
    }

我的模型定义如下,

    public class AuditZone
    {
        public AuditZone()
        {
            AuditZoneUploadedCOESDetails = new List<UploadedCOESDetails>();
            AuditZonePostcode = new List<Postcodes>();
        }


        public int Id { get; set; }
        public string Description { get; set; }     
        public bool Valid { get; set; }       
        public DateTime CreatedDate { get; set; }
        public int? CreatedBy { get; set; }
        public DateTime? ModifiedDate { get; set; }
        public int? ModifiedBy { get; set; }

        public virtual UserProfile CreatedByUser { get; set; }
        public virtual UserProfile ModifiedByUser { get; set; }

        public virtual ICollection<UploadedCOESDetails> AuditZoneUploadedCOESDetails { get; set; }
        public virtual ICollection<Postcodes> AuditZonePostcode { get; set; }
    }

我需要做的是有人获得关键属性和表名..

目前,我获得了以下代码

   TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), true).SingleOrDefault() as TableAttribute;

            // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
            string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;

            // Get primary key value (If you have more than one key column, this will need to be adjusted)
            var keyNames = dbEntry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).ToList();

            string keyName = keyNames[0].Name;

如果我在模型中添加数据注释[Key]和[Table],这是有效的。但我已经在配置中定义了它们,所以我试图不重复工作......

有什么想法吗?

0 个答案:

没有答案