【问题标题】:Entity Framework Generic Insert Method Assign Guid to Primary Key实体框架通用插入方法将 Guid 分配给主键
【发布时间】:2020-05-13 22:59:40
【问题描述】:

有没有一种方法可以通用地标识主键(始终为单列)并在通用 Insert 方法中分配 Guid:

例如我有谁 dbSet 类。两者都有一个 Guid 类型的单字段主键:

public class Person
{
   [Key]
   [Required]
   public Guid personId {get; set;}
   public string name {get; set;}
}

public class City
{
    public Guid cityId {get; set;}
    public string name (get; set;
}

我希望我能够做这样的事情:

City city = new City {
   name = "Seattle";
};
Update<City>(city);

使用这样的通用方法:

public T Insert<T>(T entity) where T : class
{
   // Instead of using code like this for each entity type
   if (entity is City)
   {
       City cEntity = entity as City
       cEntity.cityId = Guid.NewGuid();
   }

   // I want to be able to do something generically like this
   entity.PrimaryKey = Guid.NewGuid();

   // Add
   this._db.Set<T>().Add(item);
}

这很疯狂还是我应该让数据库在插入时自动将 Guid 添加到表中?

谢谢。

【问题讨论】:

    标签: c# asp.net entity-framework generics


    【解决方案1】:

    您可以使用反射找出Guid类型或具有KeyAttribute的成员

    var byType = entity.GetType().GetProperties().First(x => x.PropertyType == typeof(Guid));
    //or
    var byAtttribute = entity.GetType().GetProperties().First(x=>x.CustomAttributes.Any(a=>a.AttributeType.Name=="KeyAttribute"));
    

    然后设置值

    byType.SetValue(entity, Guid.NewGuid());
    //or
    byAttribute.SetValue(entity, Guid.NewGuid());
    

    但这保证会更慢,除非你因为某种原因需要分配一个预定义的 Guid,否则最好让数据库来处理。

    【讨论】:

      【解决方案2】:

      为id创建接口:

      public interface IHasGuid
      {
          Guid ID { get; set; }
      }
      

      然后让你的类实现那个接口:

      public class Person : IHasGuid
      {
         [Key]
         [Required]
         public Guid ID {get; set;}
         public string name {get; set;}
      }
      
      public class City : IHasGuid
      {
          public Guid ID {get; set;}
          public string name (get; set;
      }
      

      然后您可以在TIHasGuid 的任何地方访问ID 属性:

      public T Insert<T>(T entity) where T : class, IHasGuid
      {
         entity.ID = Guid.NewGuid();
      
         // ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-27
        • 2020-07-21
        • 2018-04-11
        • 2019-04-17
        • 1970-01-01
        相关资源
        最近更新 更多