开发者

Entity Framework 4.1 insert error

开发者 https://www.devze.com 2023-04-02 00:55 出处:网络
i have written a generic repository for my base windows which have a problem with. lets be more specific, there is a little poco class called Unit as following:

i have written a generic repository for my base windows which have a problem with. lets be more specific, there is a little poco class called Unit as following:

public class Unit : BaseEntity
    {
        public string Name { get; set; }

        private ICollection<Good> _goods;
        public virtual ICollection<Good> Goods
        {
            get
            {
                if(_goods==null)
                {
           开发者_C百科         return new List<Good>();
                }
                return _goods;
            }
            set { _goods = value; }
        }
    }

which is inherited from a base entity class as :

public class BaseEntity 
    {

        public int Id { get; set; }
        public override string ToString()
        {
            return Id.ToString();
        }

    }

and this is my Add section of generic repository class:

 public void Add(TEntity entity)
        {
            if (entity == null) return;
            if (Context.Entry(entity).State == EntityState.Detached)
            {
                Context.Set<TEntity>().Attach(entity);
            }
            Context.Set<TEntity>().Add(entity);
            Context.SaveChanges();

        }

before add a new record, max id is fetched from db and placed in IdTextBox and them add method of base form is called which calls aforementioned Add method of base repository. here is the problem, i get this error, "The property 'Id' is part of the object's key information and cannot be modified." there is also a mapper class that maps every property to its corresponding control which does its job fine. What is my problem?

Thanks in advance.


i figured out that this problem is occured because of auto detect changes enability which was true.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号