Question

I have table with design like that

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

I converted it to POCO class with t4 template which looks like

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; }
    }
}

now I have repository looks like

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);
        }
}

and I created category dataaccessmanager like

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;
            }


        }

it calls this.Add(category); but without insert , any idea how to solve that , the problem is that the Id of new category come with Id = 0

Was it helpful?

Solution

SaveChanges() needs to be called in Add()...

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

Or this.Commit() should be called after this.Add(category).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top