Callum Linington
Callum Linington

Reputation: 14417

ASP.NET MVC 3 Database Context Querying

I have my Database Context:

public class ProductContext : DbContext
{
    public ProductContext() : base ("DefaultConnection") {}

    public DbSet<Product> Products {get;set;}
}

and my Repository:

public class ProductRepository : IProductRepository
{
    private ProductContext _dbContext = new ProductContext();

    public IQueryable<Product> Products { get { return _dbContext.Products; } }
}

when I query my database in the Edit Action:

public ActionResult Edit(Guid id)
{
    var item = _repository.Products.FirstOrDefault(x => x.Id.Equals(id));

    return View(item);
}

I would usually use a ViewModel but this is purely to show the scenario.

When I query the database using the var item line, does EntityFramework change the state of that item.

Can I pass around that item through a multitude of Services in the Service Layer and then finally save it using my method:

public void SaveEntity<TEntity>(TEntity entityToSave) where TEntity : DbEntity
{
    if (entityToSave.Id.Equals(Guid.Empty))
        _dbContext.Set<TEntity>().Add(entityToSave);
    else
        _dbContext.Entry<TEntity>(entityToSave).State = EntityState.Modified;

    _dbContext.SaveChanges();
}

It won't throw an exception saying that there is already a Entity with the same Id as the one you're trying to Save?

Upvotes: 1

Views: 917

Answers (1)

Callum Linington
Callum Linington

Reputation: 14417

So after trial and error, it seems that this works perfectly fine, and it doesn't bring back any errors. There is one thing to look out for:

This navigation property:

public virtual Category Category { get;set; }
public Guid CategoryId { get;set; }

That could reside in the Product model has a little gotcha, that is:

When editing or saving a new Product, you should only set the CategoryId and not just the Category exclusively because you will get duplicate Category entries every time you edit or save if you use the a Category that already exist within the database...

I think you should the navigation property solely for your ease, not for use when modifying entities...

Upvotes: 1

Related Questions