The instance of entity type ‘XXXX’ cannot be tracked because another instance with the same key value for {‘XXXX’} is already being tracked.


While working my EF core Application I was getting this exception message. I fixed this issue like this

Step 1: In Insert/update method make ensure to detach the entity.

_db.Entry(localRopFiles).State = EntityState.Detached;

Step 2: If you are loading data on page load then use AsNoTracking() method

var query = await _db.LocalRopFiles.AsNoTracking().ToListAsync();

I hope this will help some one who is getting this type of exception.

How to implement EF database first approach in Asp.net Core Blazor ?


Step 1: Create the database as per as your requirement
Step 2: Install the EF Core Power Tool in Visual studio like this

https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools

Step 3: Go to the solution explorer and right click on it then EF Power Tool then Reverse Engineer as given below image

Solution Exp

Step 4:  Select the database name like this

database name

then click on OK

Step 5: Select all the required table which one we are going to use in application

Step 6:  Now Select the namespace and context name like given below

Namespace

Step 7 : Click on OK. Now this tool will generate the required model and context file in Data folder.

How to Call the Store Procedure in Entity Framework for CRUD operation


Hi All,

This is just the extension of CRUD operation in Asp.net MVC using AngularJs

In the previous post we show that we are doing database operation using Entity Framework with LINQ query. But if we have some complex logic which require multiple tables to be join then we write the logic in store procedure. So entity framework also provide the feature to map the SP in edmx file.

Now we will go by step wise for this task

Step 1: Write the SP in Database like this

CREATE PROCEDURE DeleteDept
    @Id int
	
AS
Begin
	Delete from  tblDept where Id=@Id
END
RETURN

---------------------------------------------
CREATE PROCEDURE FetchDept_OnId
    @Id int
	
AS
Begin
	Select * from  tblDept where Id=@Id
END
RETURN

---------------------------------------------
CREATE PROCEDURE FetchDeptDetails
	
AS
	SELECT * from tblDept
RETURN
-----------------------------------------
CREATE PROCEDURE InsertDept
	@DeptName Varchar(250),
	@DeptDesc Varchar(500)
AS
Begin
	Insert into tblDept(DeptName,DeptDesc) Values(@DeptName,@DeptDesc)
END
RETURN
------------------------------------------
CREATE PROCEDURE UpdateDept
    @Id int,
	@DeptName Varchar(250),
	@DeptDesc Varchar(500)
AS
Begin
	Update  tblDept Set DeptName=@DeptName, DeptDesc= @DeptDesc where Id=@Id
END
RETURN

Step 2:
Do like my previous article How to fetch data from SP in EF

Step 3: Now select the Context.tt and Model.tt file of Edmx file and run the “Run Custom Tool” like this

This will generate the DAL layer code with SP for Insert/Update/Read/Delete functionality.

Step 4: Now go to the Dept Controller and write the code for calling SP like this

using AngularCRUD.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace AngularCRUD.Controllers
{
    public class DeptController : Controller
    {
        // GET: /Dept/
        string msg = string.Empty;
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult Get_AllDepts()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                var  objDept = obj.FetchDeptDetails().ToList();
                return Json(objDept, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult Get_DeptById(string Id)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                int DeptId = int.Parse(Id);
                return Json(obj.FetchDept_OnId(DeptId), JsonRequestBehavior.AllowGet);
            }
        }

        public string Insert_Dept(tblDept dept)
        {
            if (dept != null)
            {

                using (Database1Entities obj = new Database1Entities())
                {
                    int flag= obj.InsertDept(dept.DeptName,dept.DeptDesc);
                    if (flag==1)
                    {
                      msg=  "Dept details Added Successfully";
                    }
                    return msg;
                }
            }
            else
            {
                return "Dept Details Not Inserted! Try Again";
            }

        }

        public string Update_Dept(tblDept Dept)
        {
            if (Dept != null)
            {
                
                using (Database1Entities Obj = new Database1Entities())
                {
                    int flag = Obj.UpdateDept(Dept.Id, Dept.DeptName, Dept.DeptDesc);
                    if (flag==1)
                    {
                        msg = "Dept details Updated Successfully";
                    }
                    return msg;
                }
            }
            else
            {
                return "Dept Details Not Updated! Try Again";
            }
        }  

        public string Delete_Dept(tblDept dept) 
        {
            if (dept != null)
            {
               
                using (Database1Entities obj = new Database1Entities())
                {
                   
                   int flag= obj.DeleteDept(dept.Id);

                   if (flag==1)
                   {
                       msg= "Dept details deleted Successfully";
                   }
                   return msg;
                }
            }
            else
            {
                return "Dept Details Not Deleted! Try Again";
            }
        }
    }
}

Brief introduction of all Entity Framework Version


If you are going for interview then this question might be asked.

EF 3.5

1. Basic O/RM support with Database First approach.
2. It came with VS 2008 Sp1

EF 4.0

1. POCO Support
2. Lazy loading
3. Testability improvements
4. customizable code generation and the Model First approach.
5. It came with VS 2010.

EF 4.1

1. First to available of NuGet package
2. Simplified DBContext API over ObjectContext,
3. Code First approach.
4. EF 4.1.1 patch released with bug fixing of 4.1.
5. It came with VS 2010 with NuGet package.

EF 4.3

1. Code First Migrations feature that allows a database created by Code First to be incrementally changed as your Code First model evolves.
EF 4.3.1 patch released with bug fixing of EF 4.3.
2. It came with VS 2010 with NuGet package.

EF 5.0

1. Announced EF as Open Source.
2. Introduced Enum support,
3. Table-valued functions,
4. Spatial data types,
5. Multiple-diagrams per model,
6. Coloring of shapes on the design surface and batch import of stored procedures,
7. EF Power Tools and various performance improvements.
8. Precompile SP and View.
9. It came with VS 2012 with NuGet package.

EF 6.0

1. Current release EF 6.0\6.1 is latest release of Entity Framework.
2. It includes many new features related to Code First & EF designer like asynchronous query & save,
3. Connection Resiliency,
4. Dependency resolution etc.
5. DbSet.AddRange/RemoveRange
6. Better Transaction Support
7. Database command logging
8. Pluggable pluralisation and singularization service
9. It came with VS 2012 and VS 2013 with NuGet package.

How to fetch data from StoreProcedure using Entity Framework ?


Hi

If you will create the Data model in EF using general approach then you will be not able to fetch data from SP in EF.

For fetching data from SP using EF. we can do like this

Step 1 : Add the SP and Table Name in Data Model like this

EF1

Step 2: In the data model designer, right-click on Model Browser then go to storeprocedure

EF2

Step 3: click on “Add Function Import” and configure the SP maping like image

EF3

Step 4: Click on save all and build the application

Step 5: Write the code in code behind file like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (DatabaseModel.DatabaseEntities dc = new DatabaseModel.DatabaseEntities())
        {
            //var query = dc.VW_tblEmp.Select(m => m);
            var query = dc.GetEmpName();
            Grid1.DataSource = query;
            Grid1.DataBind();
        }
    }
}

Note: Here i hope that you are aware of doing configuration on model in EF.