P
P
Paul Fawkes2019-07-16 12:59:09
ASP.NET
Paul Fawkes, 2019-07-16 12:59:09

How to fix linq to sql error?

I work with ado.net. I created a generic repository:

public class Repository<T> : IRepository<T> where T : class, IEntity
{
    protected Table<T> DataTable;
    public Repository(DataContext context)
    {
        DataTable = context.GetTable<T>();
    }

    public void Delete(T entity)
    {
        DataTable.Attach(entity);
    }

    public void Edit(T entity)
    {

    }

    public void Insert(T entity)
    {
        DataTable.InsertOnSubmit(entity);
    }

    public IQueryable<T> GetAll()
    {
        return DataTable;
    }

    public T GetById(int id)
    {
        return DataTable.Single(e => e.Id.Equals(id));
    }

    public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
    {
        return DataTable.Where(predicate);
    }
}

and want to delete object, controller:
public IActionResult DeleteProject(int id)
    {
        var model = projects.GetById(id);
        return View(model);
    }
    [HttpPost]
    public IActionResult DeleteProject(Project project)
    {
        projects.Delete(project);
        connection.SubmitChanges();
        return RedirectToAction("Index");
    }

while deleting it throws an error:
System.InvalidOperationException: Cannot remove an entity that has not been attached.

ok i make DataTable.Attache(entity)a mistake
System.Data.Linq.DuplicateKeyException: 'Cannot add an entity with a key that is already in use.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question