Я создал веб-приложение MVC с использованием репозитория & DI-подход. Я также использовал подход Code First.Проблема при подключении веб-приложения с localdb с использованием файла DataContext и файла webConfig
Вот мой DataContext файл:
namespace EfRepPatTest.Data
{
public class DataContext : DbContext, IDbContext
{
public new IDbSet<TEntity> Set<TEntity>() where TEntity: class
{
return base.Set<TEntity>();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType &&
type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
}
}
Я определил подключения строки в файле Web.Config, как показано ниже:
<add name="DataContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\eCommerce.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
Пожалуйста, обратите внимание, здесь я упомянул одно имя строки подключения и мой контекстный файл.
Вот мой пост метод:
[HttpPost]
public ActionResult Create(CategoryModel model)//FormCollection collection
{
try
{
// TODO: Add insert logic here
if (model == null)
return View(model);
var category = new Category();
category.Name = model.Name;
categoryService.Insert(category);
return RedirectToAction("Index");
}
catch
{
return View(model);
}
}
CategoryService:
public class CategoryService : ICategoryService
{
private IRepository<Category> _categoryRepository;
public CategoryService(IRepository<Category> categoryRepository)
{
this._categoryRepository = categoryRepository;
}
public void Insert(Category category)
{
if (category == null)
throw new ArgumentNullException("Category");
_categoryRepository.Insert(category);
}
}
RepositoryService:
public class RepositoryService<TEntity> : IRepository<TEntity> where TEntity: class
{
private IDbContext _context;
private IDbSet<TEntity> Entities
{
get { return this._context.Set<TEntity>(); }
}
public RepositoryService(IDbContext context)
{
this._context = context;
}
public void Insert(TEntity entity)
{
Entities.Add(entity);
}
}
При запуске приложения в первый раз он будет созд ел местный дБ. Но когда я собираюсь вставлять данные, я не получал никаких ошибок от приложения и не вставлял мои данные в БД.
В чем причина этого? Что я здесь сделал неправильно?
Любая помощь приветствуется!
показать код, который вставляет данные –
Обновленный вопрос – Ankita
Что такое 'categoryService'? –