其他分享
首页 > 其他分享> > 用自定义属性实现复合主键的思路

用自定义属性实现复合主键的思路

作者:互联网

使用efcore的时候,使用复合主键来表示实体,很多官网推荐

[Key("",Order)]

这种方式来实现,但是很大程度上会报错。

“the entity type '' has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKEey' in 'OnModelCreating'”

使用自定义属性

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
    public class CompositeKeysAttribute : Attribute
    {
        private string name;
        public int Order;

        public CompositeKeysAttribute(string name)
        {
            this.name = name;
            Order = 1;
        } 
    }
}

 

在OnModelCreating中设置key

 

  void AdKeyAction(ModelBuilder modelBuilder)
        {
            foreach (var mutableEntityType in modelBuilder.Model.GetEntityTypes())
            {  
                if (mutableEntityType.ClrType == null)
                    continue;
                var files = mutableEntityType.ClrType.GetMembers().Where(c=>c.CustomAttributes.Any(c=>c.AttributeType==typeof(CompositeKeysAttribute))); 
                var properties = new List<string>();
                foreach (var f in files)
                {
                    properties.Add(f.Name); 
                }
                if (properties.Count > 0)
                {
                    modelBuilder.Entity(mutableEntityType.ClrType).HasKey(properties.ToArray()); 
                } 
            }
        }

使用的时候

public class User
{
   [CompositeKeys("UserName",Order=1)] 

public string UserName{set;get;}
  [CompositeKeys("UserArea",Order=2)] 
  public string UserArea{get;set;} 
}

 

标签:properties,string,自定义,mutableEntityType,复合,Order,主键,public,name
来源: https://www.cnblogs.com/lecone/p/16607537.html