使用实体保存对象不起作用

时间:2014-05-02 21:52:53

标签: c# entity-framework-5 poco

我有像这样的设计表

Create table [dbo].[Category](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ShortString] varchar(100),
[Description] varchar(100), 
CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

我用t4模板将它转换为POCO类,看起来像

namespace ArabicEWorld.Model
{
    using System;
    using System.Collections.Generic;

    public partial class Category
    {
        public Category()
        {
            this.Nouns = new HashSet<Noun>();
        }

        public int Id { get; set; }
        public string ShortString { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Noun> Nouns { get; set; }
    }
}

现在我的存储库看起来像

public abstract class Repository<T> : IRepository<T>, IDisposable where T : class
    {

        private ClassesDatabasdEntities Context;
        protected Repository()
        {
            Context = new ClassesDatabasdEntities ();
        }
 public void Commit()
        {
            Context.SaveChanges();
        }
        public void Add(T entity)
        {
            Context.CreateObjectSet<T>().AddObject(entity);
        }
        public void Update(T entity)
        {
            Context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
            Context.SaveChanges();
        }
        public void Delete(T entity)
        {
            Context.DeleteObject(entity);
            Context.SaveChanges();
        }
        public void Dispose()
        {
            if (Context != null)
            {
                Context.Dispose();
            }
            GC.SuppressFinalize(this);
        }
}

我创建了类别dataaccessmanager,如

public class CategoryDataAccessManager : Repository<Model.Category>, ICategoryDataAccessManager
    {
        public bool SaveCategory(Model.Category category)
        {
            try
            {
                if (this.Get(t => t.Id == category.Id).Any())
                {
                    this.Update(category);
                }
                else
                {
                    this.Add(category);

                }

                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }

它调用this.Add(category);但没有插入,任何想法如何解决,问题是新类别的Id来自Id = 0

1 个答案:

答案 0 :(得分:1)

需要在SaveChanges() ...

中调用

Add()

public void Add(T entity)
{
    Context.CreateObjectSet<T>().AddObject(entity);
    Context.SaveChanges();
}

this.Commit()之后应调用this.Add(category)