public virtual void CreateKey(IActivationLog log)
 {
     if (this.Key != null) //protect against multiple processing
     {
         return;
     }
     // we initially assign temp names
     this.Key = new EntityKeyInfo(HostEntity, KeyType, HostMember, this.Alias);
     // add members
     if (HostMember != null)
     {
         Key.KeyMembers.Add(new EntityKeyMemberInfo(HostMember, false));
     }
     else
     {
         // it will add errors if it fails
         HostEntity.TryParseKeySpec(this.MemberNames, log, out Key.KeyMembers, ordered: true);
     }
     // construct name
     Key.ExplicitDbKeyName = this.DbKeyName;
     // PK
     if (KeyType.IsSet(KeyType.PrimaryKey))
     {
         if (HostEntity.PrimaryKey == null)
         {
             HostEntity.PrimaryKey = Key;
             Key.KeyMembers.Each(km => km.Member.Flags |= EntityMemberFlags.PrimaryKey);
         }
         else
         {
             log.Error("Entity {0} has more than one Primary Key specified.", GetHostRef());
         }
     }
 }
        /// <summary>
        /// 尝试取缓存项,若不存在则自动加载
        /// </summary>
        /// <param name="groupKey"></param>
        /// <param name="isAutoLoad">是否要自动加载</param>
        /// <param name="itemData"></param>
        /// <param name="loadStatus"></param>
        /// <returns></returns>
        protected bool TryGetCacheItem <TValue>(object[] keys, bool isAutoLoad, out TValue itemData)
        {
            CheckLoad();
            itemData = default;

            string groupKey = EntityKeyInfo.CreateKeyCode(keys);

            if (string.IsNullOrEmpty(groupKey))
            {
                return(false);
            }
            //处理分组方法加载,在内存中存在且加载不出错时,才不需要重读
            if (Collection.TryGetValue(groupKey, out object itemSet))
            {
                itemData = (TValue)itemSet;
                return(true);
            }
            if (isAutoLoad && LoadItemFactory(keys, false))
            {
                if (Collection.TryGetValue(groupKey, out itemSet))
                {
                    itemData = (TValue)itemSet;
                    return(true);
                }
            }
            return(false);
        }
 private void AddParametersFromKey(EntityCommand command, EntityKeyInfo key)
 {
     foreach (var keyMember in key.ExpandedKeyMembers)
     {
         command.Parameters.Add(new EntityCommandParameter(keyMember.Member));
     }
 }
Beispiel #4
0
        private string GetKeyAttribute(EntityKeyInfo key, bool onProperty)
        {
            var attrName = GetKeyAttributeName(key.KeyType);
            var args     = new List <string>();

            if (!onProperty)
            {
                args.Add(DQuote(GetKeyColumnList(key)));
            }
            if (key.IndexFilter != null)
            {
                args.Add("Filter = " + DQuote(key.IndexFilter.Template.OriginalTemplate));
            }
            if (key.IncludeMembers.Count > 0)
            {
                var sInc = string.Join(",", key.IncludeMembers.Select(m => m.MemberName));
                args.Add("IncludeMembers = " + DQuote(sInc));
            }
            if (key.KeyType.IsSet(KeyType.PrimaryKey) && key.KeyType.IsSet(KeyType.Clustered))
            {
                args.Add("Clustered=true");
            }
            if (args.Count == 0)
            {
                return(attrName);
            }
            var result = attrName + "(" + string.Join(", ", args) + ")";

            return(result);
        }
Beispiel #5
0
        private void ProcessEntityRefMember(EntityMemberInfo member)
        {
            // Check if EntityRef attr is present
            var entRefAttr = member.Attributes.OfType <EntityRefAttribute>().FirstOrDefault();

            var entity       = member.Entity;
            var propName     = entity.EntityType.Name + "." + member.MemberName;
            var targetType   = member.DataType;
            var targetEntity = this.Model.GetEntityInfo(targetType);

            if (targetEntity == null)
            {
                Log.Error("Reference property {0}: target entity not found: {1}", propName, targetType);
                return;
            }

            //find target key; usually it is PK on target entity, but MS SQL allows linking to any unique key
            // EntityRef attr might specify target unique key
            var targetKey = targetEntity.PrimaryKey;
            var targetUniqueIndexAlias = entRefAttr?.TargetUniqueIndexAlias;

            if (!string.IsNullOrEmpty(targetUniqueIndexAlias))
            {
                targetKey = FindCreateKeyByAlias(targetEntity, targetUniqueIndexAlias);
                if (targetKey == null)
                {
                    Log.Error("Property {0}: Invalid target index alias '{1}' in EntityRef attrribute, index not found on target entity {2}.",
                              propName, targetUniqueIndexAlias, targetEntity.EntityType);
                    return;
                }
                if (!targetKey.KeyType.IsSet(KeyType.Unique))
                {
                    Log.Error("Property {0}: Invalid target Index in EntityRef attrribute; Index {1} is not Unique.", propName, targetUniqueIndexAlias);
                    return;
                }
            }
            //Create foreign key
            var fk = new EntityKeyInfo(entity, KeyType.ForeignKey, member);

            fk.IsCopyOf = targetKey;
            fk.KeyMembers.Add(new EntityKeyMemberInfo(member, false));
            var refInfo = member.ReferenceInfo = new EntityReferenceInfo(member, fk, targetKey);

            // if there's EntitRef attr, apply its props if specified
            if (entRefAttr != null)
            {
                if (!string.IsNullOrEmpty(entRefAttr.ForeignKeyName))
                {
                    refInfo.FromKey.Name = entRefAttr.ForeignKeyName;
                }
                if (!string.IsNullOrWhiteSpace(entRefAttr.KeyColumns))
                {
                    refInfo.ForeignKeyColumns = entRefAttr.KeyColumns;
                }
            }
            if (targetEntity.Flags.IsSet(EntityFlags.HasIdentity))
            {
                entity.Flags |= EntityFlags.ReferencesIdentity;
            }
        }
Beispiel #6
0
        public TEntity Find(params object[] keys)
        {
            string key    = EntityKeyInfo.CreateKeyCode(keys);
            var    entity = cacheManager.Get <TEntity>(key, Region);

            return(entity);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entity"></param>
        public TEntity Add(TEntity entity)
        {
            var key = EntityKeyInfo.GetPrimaryKey(entity);

            cacheManager.Add(key, entity, Region);
            return(entity);
        }
Beispiel #8
0
        public TEntity Delete(TEntity entity)
        {
            var key = EntityKeyInfo.GetPrimaryKey(entity);

            cacheManager.Remove(key, Region);
            return(entity);
        }
        /// <summary>
        /// cachemanager 不支持findall
        /// 使用redis。HKEYS 查询所有的key然后再查找key是否包含keyvalue可以实现(待做)
        /// https://github.com/MichaCo/CacheManager/issues/225
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keyValues"></param>
        /// <returns></returns>
        public override IEnumerable <T> OnFindAllExecuting <T>(params object[] keyValues)
        {
            var efRepository = services.GetService(DbType) as IFindExpressionRepository <T>;

            var props = EntityKeyInfo.GetGroupProps <T>();

            var query = efRepository.FindQuery();

            var        item       = Expression.Parameter(typeof(T), "item");
            Expression expression = null;

            for (int i = 0; i < props.Count; i++)
            {
                var prop = Expression.Property(item, props[i].Name);
                var soap = Expression.Constant(keyValues[i]);

                var equal = Expression.Equal(prop, soap);

                if (expression == null)
                {
                    expression = equal;
                }
                else
                {
                    expression = Expression.And(
                        expression,
                        equal
                        );
                }
            }
            var lambda = Expression.Lambda <Func <T, bool> >(expression, item);

            return(query.Where(lambda).ToList());
        }
Beispiel #10
0
        public EntityKey(EntityKeyInfo key, params object[] values)
        {
            var keyCount = key.ExpandedKeyMembers.Count;

            Util.Check(keyCount == values.Length, "Invalid number of key values, expected: {0}, provided: {1}.", keyCount, values.Length);
            KeyInfo = key;
            Values  = values;
        }//constructor
Beispiel #11
0
 public static SpecialLinqCommand CreateCheckAnyChildRecords(EntityKeyInfo childKey, EntityRecord record)
 {
     childKey.SqlCacheKey_ChildExists = childKey.SqlCacheKey_ChildExists ??
                                        SqlCacheKeyBuilder.BuildSpecialSelectKey(Tag_ExistsByKey, childKey.Entity.Name,
                                                                                 childKey.Name, LockType.None, null);
     return(new SpecialLinqCommand(record.Session, childKey.SqlCacheKey_ChildExists, childKey,
                                   LockType.None, null, record.PrimaryKey.Values, Setup_CheckChildExists));
 }
Beispiel #12
0
 public EntityCommand(string commandName, string description, EntityCommandKind kind, EntityInfo entity, EntityKeyInfo selectKey = null)
     : this(commandName, description, kind)
 {
     TargetEntityInfo = entity;
       Area = entity.Area;
       TargetEntityType = entity.EntityType;
       SelectKey = selectKey;
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="dataList"></param>
 /// <param name="periodTime"></param>
 /// <param name="isReplace"></param>
 /// <returns></returns>
 protected bool InitCache(List <TEntity> dataList, bool isReplace)
 {
     Collection.Clear();
     foreach (var data in dataList)
     {
         Collection.Add(EntityKeyInfo.GetPrimaryKey(data), data);
     }
     return(true);
 }
Beispiel #14
0
 public IEnumerable <TEntity> AddRange(IEnumerable <TEntity> entitiesToAdd)
 {
     foreach (var entity in entitiesToAdd)
     {
         var key = EntityKeyInfo.GetPrimaryKey(entity);
         cacheManager.Add(key, entity, Region);
     }
     return(entitiesToAdd);
 }
Beispiel #15
0
        public TEntity Update(TEntity entity)
        {
            var key = EntityKeyInfo.GetPrimaryKey(entity);

            return(cacheManager.AddOrUpdate(key, Region, entity, (oldValue) =>
            {
                return entity;
            }));
        }
Beispiel #16
0
 public DbKeyInfo(string name, DbTableInfo table, KeyType type, EntityKeyInfo entityKey = null)
     : base(table.DbModel, table.Schema, DbObjectType.Key, entityKey)
 {
     Name      = name;
     Table     = table;
     KeyType   = type;
     EntityKey = entityKey;
     table.Keys.Add(this);
     base.GlobalName = DbModelHelper.GetGlobalName(table.Schema, name);
 }
Beispiel #17
0
        public void PrefixWithMultipleSegmentsConstantStringsObjectPropertiesTest()
        {
            var keyInfo = new EntityKeyInfo <TestModel>("UR", e => new { PrefixNameDoesntMatter = "LF", e.LastName, e.FirstName });

            var key = keyInfo.KeyGetter.Invoke(_testModel);

            Assert.AreEqual(key, "UR__LF__Liu__Yue");

            var testModel = new TestModel();

            keyInfo.KeySetter.Invoke(testModel, "UR__LF__Liu__Yue");
            Assert.AreEqual(testModel.FirstName, "Yue");
            Assert.AreEqual(testModel.LastName, "Liu");
            Assert.AreEqual(testModel.Description, null);

            keyInfo.KeySetter.Invoke(testModel, "UR__LF__Liu__");
            Assert.AreEqual(testModel.FirstName, string.Empty);
            Assert.AreEqual(testModel.LastName, "Liu");
            Assert.AreEqual(testModel.Description, null);

            keyInfo.KeySetter.Invoke(testModel, "UR__LF____");
            Assert.AreEqual(testModel.FirstName, string.Empty);
            Assert.AreEqual(testModel.LastName, string.Empty);
            Assert.AreEqual(testModel.Description, null);

            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, null));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, string.Empty));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, ",="));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, ",-"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "Liu"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, ","));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, ",L"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, ",Liu"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "Liu__Yue"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "__Liu__Yue"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "LFLiu__Yue"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "LF__Liu"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "LF__Liu_"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "LF__"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "LF___"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__,="));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__,-"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__Liu"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__,"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__,L"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__,Liu"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__Liu__Yue"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR____Liu__Yue"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__LFLiu__Yue"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__LF__Liu"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__LF__Liu_"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__LF__"));
            Expect.Exception <FormatException>(() => keyInfo.KeySetter.Invoke(testModel, "UR__LF___"));
        }
        public EntityCommand BuildCrudSelectByKeyCommand(EntityKeyInfo key, string filter = null, string nameSuffix = null)
        {
            var entity   = key.Entity;
            var procName = entity.Name + "_SelectBy" + key.GetMemberNames(string.Empty, removeUnderscore: true) + nameSuffix;
            var descr    = "Selects entity(ies) by key.";
            var cmd      = AddCommand(procName, descr, EntityCommandKind.SelectByKey, entity, key);

            cmd.Filter = filter;
            AddParametersFromKey(cmd, key);
            return(cmd);
        }
Beispiel #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public TEntity Add(TEntity value)
        {
            string personalId = EntityKeyInfo.GetGroupKey(value);

            if (string.IsNullOrEmpty(personalId))
            {
                throw new ArgumentNullException("t", "t.PersonalId is null");
            }

            if (!RunAspect(attribute => attribute.OnAddExecuting(value)))
            {
                return(default);
Beispiel #20
0
 public SpecialLinqCommand(EntitySession session, string sqlCacheKey,
                           EntityKeyInfo key, LockType lockType, List <EntityKeyMemberInfo> orderBy,
                           object[] paramValues, Action <SpecialLinqCommand> setupAction)
     : base(session, LinqCommandKind.Special, LinqOperation.Select)
 {
     this.SqlCacheKey = sqlCacheKey;
     Key           = key;
     base.LockType = lockType;
     OrderBy       = orderBy;
     ParamValues   = paramValues;
     SetupAction   = setupAction;
 }
Beispiel #21
0
 public bool KeyIsLoaded(EntityKeyInfo key)
 {
     for (int i = 0; i < key.ExpandedKeyMembers.Count; i++)
     {
         var valueIndex = key.ExpandedKeyMembers[i].Member.ValueIndex;
         var v          = ValuesModified[valueIndex] ?? ValuesOriginal[valueIndex];
         if (v == null)
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #22
0
 public EntityCommand BuildCrudSelectByKeyArrayCommand(EntityKeyInfo key)
 {
     if (key.ExpandedKeyMembers.Count > 1)
     return null;
       var member0 = key.ExpandedKeyMembers[0].Member;
       var entity = key.Entity;
       var procName = entity.Name + "_SelectByArrayOf_" + key.GetMemberNames(string.Empty, removeUnderscore: true);
       var descr = "Selects entities by array of key values.";
       var cmd = AddCommand(procName, descr, EntityCommandKind.SelectByKeyArray, entity, key);
       var prmType = typeof(IEnumerable<>).MakeGenericType(member0.DataType);
       cmd.Parameters.Add(new EntityCommandParameter("Values", prmType, 0, null));
       return cmd;
 }
Beispiel #23
0
        }//method

        public bool KeyIsNull(EntityKeyInfo key)
        {
            for (int i = 0; i < key.ExpandedKeyMembers.Count; i++)
            {
                var valueIndex = key.ExpandedKeyMembers[i].Member.ValueIndex;
                var v          = ValuesModified[valueIndex] ?? ValuesOriginal[valueIndex];
                // Note: transient values in new record might be null
                if (v != DBNull.Value)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #24
0
 public bool KeyMatches(EntityKeyInfo keyInfo, object[] keyValues)
 {
     for (int i = 0; i < keyInfo.ExpandedKeyMembers.Count; i++)
     {
         var member     = keyInfo.ExpandedKeyMembers[i].Member;
         var thisValue  = GetValue(member);
         var otherValue = keyValues[i];
         var eq         = member.AreValuesEqual(thisValue, otherValue);
         if (!eq)
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #25
0
        private string GetKeyColumnList(EntityKeyInfo key)
        {
            var specs = new string[key.KeyMembers.Count];

            for (int i = 0; i < key.KeyMembers.Count; i++)
            {
                var keyMember  = key.KeyMembers[i];
                var memberSpec = keyMember.Member.MemberName;// ?? keyMember.Member.MemberName;
                if (keyMember.Desc)
                {
                    memberSpec += ":DESC";
                }
                specs[i] = memberSpec;
            }
            return(string.Join(",", specs));
        }
        public EntityCommand BuildCrudSelectByKeyArrayCommand(EntityKeyInfo key)
        {
            if (key.ExpandedKeyMembers.Count > 1)
            {
                return(null);
            }
            var member0  = key.ExpandedKeyMembers[0].Member;
            var entity   = key.Entity;
            var procName = entity.Name + "_SelectByArrayOf_" + key.GetMemberNames(string.Empty, removeUnderscore: true);
            var descr    = "Selects entities by array of key values.";
            var cmd      = AddCommand(procName, descr, EntityCommandKind.SelectByKeyArray, entity, key);
            var prmType  = typeof(IEnumerable <>).MakeGenericType(member0.DataType);

            cmd.Parameters.Add(new EntityCommandParameter("Values", prmType, 0, null));
            return(cmd);
        }
 public override void Apply(AttributeContext context, Attribute attribute, EntityMemberInfo member)
 {
     if (member.Kind != MemberKind.EntityRef) {
     context.Log.Error("EntityRef attribute may be used only on properties that are references to other entities. Property: {0}.{1}",
     member.Entity.Name, member.MemberName);
     return;
       }
       var entity = member.Entity;
       // Create reference info
       var targetType = member.DataType; //.Property.PropertyType;
       var targetEntity = context.Model.GetEntityInfo(targetType);
       Util.Check(targetEntity != null, "Target entity not found: {0}", targetType);
       //Create foreign key
       ForeignKeyName = ForeignKeyName ?? "FK_" + entity.Name + "_" + member.MemberName;
       var fk = new EntityKeyInfo(ForeignKeyName, KeyType.ForeignKey, entity, member);
       fk.KeyMembers.Add(new EntityKeyMemberInfo(member, false));
       member.ReferenceInfo = new EntityReferenceInfo(member, fk, targetEntity.PrimaryKey);
       member.ReferenceInfo.ForeignKeyColumns = this.KeyColumns;
 }
Beispiel #28
0
 //Verify values and create key
 public static EntityKey CreateSafe(EntityKeyInfo key, params object[] values)
 {
     //Verify
     Util.Check(key.ExpandedKeyMembers.Count == values.Length,
                "EntityKeyValue constructor: values count does not match key members count. Key={0}", key);
     for (int i = 0; i < values.Length; i++)
     {
         var value = values[i];
         if (value == null)
         {
             continue;
         }
         var memberType = key.ExpandedKeyMembers[i].Member.DataType;
         var valueType  = value.GetType();
         Util.Check(memberType.IsAssignableFrom(valueType), "Invalid key value [{0}] (type: {1}); expected {2}.",
                    value, valueType, memberType);
     }
     return(new EntityKey(key, values));
 }
Beispiel #29
0
        public static EntityKey KeyFromString(EntityKeyInfo key, string valueString)
        {
            if (key.ExpandedKeyMembers.Count == 1) //shortcut
            {
                var m0 = key.ExpandedKeyMembers[0].Member;
                var v  = m0.ValueFromStringRef(m0, valueString);
                var kv = new EntityKey(key, new object[] { v });
                return(kv);
            }
            //complex keys
            var sValues = valueString.Split(';');
            var values  = new object[key.ExpandedKeyMembers.Count];

            for (int i = 0; i < values.Length; i++)
            {
                var m = key.ExpandedKeyMembers[i].Member;
                values[i] = m.ValueFromStringRef(m, sValues[i]);
            }
            return(new EntityKey(key, values));
        }
        public override void Apply(AttributeContext context, Attribute attribute, EntityMemberInfo member)
        {
            if (member.Kind != MemberKind.EntityRef)
            {
                context.Log.Error("EntityRef attribute may be used only on properties that are references to other entities. Property: {0}.{1}",
                                  member.Entity.Name, member.MemberName);
                return;
            }
            var entity = member.Entity;
            // Create reference info
            var targetType   = member.DataType; //.Property.PropertyType;
            var targetEntity = context.Model.GetEntityInfo(targetType);

            Util.Check(targetEntity != null, "Target entity not found: {0}", targetType);
            //Create foreign key
            ForeignKeyName = ForeignKeyName ?? "FK_" + entity.Name + "_" + member.MemberName;
            var fk = new EntityKeyInfo(ForeignKeyName, KeyType.ForeignKey, entity, member);

            fk.KeyMembers.Add(new EntityKeyMemberInfo(member, false));
            member.ReferenceInfo = new EntityReferenceInfo(member, fk, targetEntity.PrimaryKey);
            member.ReferenceInfo.ForeignKeyColumns = this.KeyColumns;
        }
Beispiel #31
0
 // regular, non-foreign key
 private bool ExpandRegularKey(EntityKeyInfo key)
 {
     key.ExpandedKeyMembers.Clear();
     if (!ExpandRefMembers(key.KeyMembers.Select(km => km.Member).ToList()))
     {
         return(false);
     }
     if (!ExpandRefMembers(key.IncludeMembers))
     {
         return(false);
     }
     // Key members
     foreach (var km in key.KeyMembers)
     {
         var member = km.Member;
         if (member.Kind == EntityMemberKind.EntityRef)
         {
             key.ExpandedKeyMembers.AddRange(member.ReferenceInfo.FromKey.ExpandedKeyMembers);
         }
         else
         {
             key.ExpandedKeyMembers.Add(km);
         }
     } //foreach km
     // include members
     foreach (var member in key.IncludeMembers)
     {
         if (member.Kind == EntityMemberKind.EntityRef)
         {
             key.ExpandedIncludeMembers.AddRange(member.ReferenceInfo.FromKey.ExpandedKeyMembers.Select(km => km.Member));
         }
         else
         {
             key.ExpandedIncludeMembers.Add(member);
         }
     } //foreach km
     return(true);
 }     //method
Beispiel #32
0
        // these are not key names in db, we assign DbKey.Name in DbModelBuilder using some special code
        public static string ConstructKeyName(this EntityKeyInfo key)
        {
            Util.Check(key.IsExpanded(), "KeyMembers list must be expanded, cannot construct name. Entity: {0}, keytype: {1}",
                       key.Entity.Name, key.KeyType);
            var entity = key.Entity;
            var tName  = entity.TableName ?? entity.Name;
            var prefix = GetKeyNamePrefix(key.KeyType);

            if (key.KeyType.IsSet(KeyType.PrimaryKey))
            {
                return(prefix + tName);
            }
            else if (key.KeyType.IsSet(KeyType.ForeignKey))
            {
                var target = key.OwnerMember.ReferenceInfo.ToKey.Entity;
                return(prefix + tName + "_" + (target.TableName ?? target.Name));
            }
            else
            {
                var    members     = key.GetMemberNames();
                string memberNames = string.Join(string.Empty, members).Replace("_", string.Empty); //remove underscores in names
                return(prefix + tName + "_" + memberNames);
            }
        }
Beispiel #33
0
 private bool ExpandKey(EntityKeyInfo key)
 {
     if (key.IsExpanded())
     {
         return(true);
     }
     if (_keysInExpansion.Contains(key))
     {
         Log.LogError($"Cannot expand key/index {key.GetFullRef()}, ran into key circular reference.");
         return(false);
     }
     try {
         _keysInExpansion.Add(key);
         if (key.KeyType.IsSet(KeyType.ForeignKey))
         {
             return(ExpandForeignKey(key));
         }
         ExpandRegularKey(key);
     } finally {
         _keysInExpansion.Remove(key);
     }
     key.HasIdentityMember = key.ExpandedKeyMembers.Any(m => m.Member.Flags.IsSet(EntityMemberFlags.Identity));
     return(true);
 }
Beispiel #34
0
 private string GetKeyColumnList(EntityKeyInfo key)
 {
     var specs = new string[key.KeyMembers.Count];
       for (int i = 0; i < key.KeyMembers.Count; i++) {
     var keyMember = key.KeyMembers[i];
     var memberSpec = keyMember.Member.MemberName;// ?? keyMember.Member.MemberName;
     if (keyMember.Desc)
       memberSpec += ":DESC";
     specs[i] = memberSpec;
       }
       return string.Join(",", specs);
 }
Beispiel #35
0
 private string GetKeyAttribute(EntityKeyInfo key, bool onProperty)
 {
     var attrName = GetKeyAttributeName(key.KeyType);
       var args = new List<string>();
       if(!onProperty)
     args.Add(DQuote(GetKeyColumnList(key)));
       if(!string.IsNullOrWhiteSpace(key.Filter))
     args.Add("Filter = " + DQuote(key.Filter));
       if(key.IncludeMembers.Count > 0) {
     var sInc = string.Join(",", key.IncludeMembers.Select(m => m.MemberName));
     args.Add("IncludeMembers = " + DQuote(sInc));
       }
       if(key.KeyType.IsSet(KeyType.PrimaryKey) && key.KeyType.IsSet(KeyType.Clustered))
     args.Add("IsClustered=true");
       if(args.Count == 0)
     return attrName;
       var result = attrName + "(" + string.Join(", ", args) + ")";
       return result;
 }
Beispiel #36
0
 public bool KeyIsLoaded(EntityKeyInfo key)
 {
     for(int i = 0; i < key.ExpandedKeyMembers.Count; i++) {
     var valueIndex = key.ExpandedKeyMembers[i].Member.ValueIndex;
     var v = ValuesModified[valueIndex] ?? ValuesOriginal[valueIndex];
     if(v == null) return false;
       }
       return true;
 }
Beispiel #37
0
 public bool KeyIsNull(EntityKeyInfo key)
 {
     for(int i = 0; i < key.ExpandedKeyMembers.Count; i++) {
     var valueIndex = key.ExpandedKeyMembers[i].Member.ValueIndex;
     var v = ValuesModified[valueIndex] ?? ValuesOriginal[valueIndex];
     // Note: transient values in new record might be null
     if(v != DBNull.Value) return false;
       }
       return true;
 }
Beispiel #38
0
 public bool KeyMatches(EntityKeyInfo keyInfo, object[] keyValues)
 {
     for(int i = 0; i < keyInfo.ExpandedKeyMembers.Count; i++) {
     var member = keyInfo.ExpandedKeyMembers[i].Member;
     var thisValue = GetValue(member);
     var otherValue = keyValues[i];
     var eq = member.AreValuesEqual(thisValue, otherValue);
     if(!eq)
       return false;
       }
       return true;
 }
Beispiel #39
0
 public EntityCommand BuildCrudSelectByKeyCommand(EntityKeyInfo key, string filter = null, string nameSuffix = null)
 {
     var entity = key.Entity;
       var procName = entity.Name + "_SelectBy" + key.GetMemberNames(string.Empty, removeUnderscore: true) + nameSuffix;
       var descr = "Selects entity(ies) by key.";
       var cmd = AddCommand(procName, descr, EntityCommandKind.SelectByKey, entity, key);
       cmd.Filter = filter;
       AddParametersFromKey(cmd, key);
       return cmd;
 }
Beispiel #40
0
 private bool IsPropertyKey(EntityKeyInfo key)
 {
     if (key.KeyMembers.Count != 1)  return false;
       if(key.KeyMembers[0].Desc) return false;
       // Only Index or PK - but not ForeignKey; FK is hidden key, without attribute
       bool isIndexOrPk = key.KeyType.IsSet(KeyType.Index | KeyType.PrimaryKey);
       if (!isIndexOrPk)
     return false;
       //if it is a key on fk column that is NOT explicitly exposed as property
       if (key.KeyMembers.Any(km => km.Member.Flags.IsSet(EntityMemberFlags.ForeignKey)))
     return false;
       return true;
 }
Beispiel #41
0
 private EntityCommand AddCommand(string commandName, string description, EntityCommandKind kind, EntityInfo entity, EntityKeyInfo selectKey = null)
 {
     var command = new EntityCommand(commandName, description, kind, entity, selectKey);
       _model.AddCommand(command);
       return command;
 }
Beispiel #42
0
 public DbKeyInfo(string name, DbTableInfo table, KeyType type, EntityKeyInfo entityKey = null)
     : base(table.DbModel, table.Schema, DbObjectType.Key, entityKey)
 {
     Name = name;
       Table = table;
       KeyType = type;
       EntityKey = entityKey;
       table.Keys.Add(this);
       base.GlobalName = DbModelHelper.GetGlobalName(table.Schema, name);
 }
Beispiel #43
0
 private void AddParametersFromKey(EntityCommand command, EntityKeyInfo key)
 {
     foreach (var keyMember in key.ExpandedKeyMembers)
     command.Parameters.Add(new EntityCommandParameter(keyMember.Member));
 }