检测实体是否是新的 [英] Detect if a Entity is new

查看:52
本文介绍了检测实体是否是新的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试以通用方式检测实体是否为新实体。我想避免数据库之旅。所以我会检查id属性是null还是零。但是有没有可能检测到id属性(也是通用的)?我没有找到
包含有关该实体的任何信息的任何元数据。



Mattia Baldinger http://www.mbaldinger.com/

Hi there, I'm trying to detect in a generic way if a entity is a new. I want to avoid a database roun trip. So i would check if the id property is null or zero. But is there any possibility to detect the id property (also in a generic way)? I didn't found any metadata which contains any information about the entity.


Mattia Baldinger http://www.mbaldinger.com/

推荐答案

不确定DbContext这可以变得更简单但你可以做这样的事情

Not sure with DbContext this can be made simpler but u can do something like this

 

public bool ExistsInDatabase<T>(T obj) where T:class
        {
            bool exists = false;
            var ctx = ((IObjectContextAdapter)this).ObjectContext;
            var entry = this.Entry(obj);
            if (entry.State != EntityState.Detached)
            {
                var set = Context.CreateObjectSet<T>().EntitySet;
                var keyprop = set.ElementType.KeyMembers.First();
                //if the key is integer we can check based on if id > 0 or not
                if (keyprop.TypeUsage.EdmType.Name == "Int32")
                {
                    int keyval = entry.CurrentValues.GetValue<int>(keyprop.Name);
                    if (keyval > 0)
                    {
                        exists = true;
                    }
                }
                else
                {
                    var databasevalues = entry.GetDatabaseValues();
                    if (databasevalues != null)
                    {
                        exists = true;
                    }
                }
            }
            return exists;
        }


 var db = new NorthWindEntities();
            var cat = db.Categories.AsNoTracking().First();
            db.Entry<Category>(cat).State = System.Data.EntityState.Added;
            var isnew = db.ExistsInDatabase<Category>(cat);
            Console.WriteLine(isnew);


 


这篇关于检测实体是否是新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆