【发布时间】:2014-06-19 16:36:46
【问题描述】:
我有这样设计的桌子
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);
}
}
我创建了像
这样的类别数据访问管理器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
【问题讨论】:
标签: c# entity-framework-5 poco