none
Inserting data to Database using Entity Framework with Foreign key relation ship RRS feed

  • Question

  • Hi All,

    I am facing a strange issue when I insert a record into the DB with the help of entity framework. I am using code first approach.

    I have a User table with the columns Id, UserName, Category, CreatedDate, CreatedBy and Status_Id.

    Here Status_Id is the foreign key relation with the table status, which has the columns Id, StatusName and InternalName.

    When I try to insert the record using

    public void InsertUser(User user)
            {
                context.Users.Add(user);
                   context.SaveChanges();
    	}


    it makes an entry in both the user table as well as in the status table. I am consuming the above method with the following code

    [TestMethod]
            public void AddUsers()
            {
                BaseDBContext objBaseDBContext = new BaseDBContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
                IUserRepository objUserRepository = new UserRepository();
                IStatusRepository objStatusRepository = new StatusRepository();
                User objUser = new User();
                Status objstatus = new Status();
                objstatus = objStatusRepository.GetStatusByID(1);
                objUser.UserName = "Raghul Varma";
                objUser.Category = "Admin";
                objUser.CreatedBy = "Admin";
                objUser.CreatedDate = DateTime.Now;
                objUser.Statuses = objstatus;
                objUserRepository.InsertUser(objUser);
           }

    What am I doing wrong, Please help.

    Thanks in advance.

    Regards,

    Raghul


    Regards, Raghul

    • Moved by CoolDadTx Wednesday, October 16, 2013 1:55 PM EF related
    Wednesday, October 16, 2013 9:59 AM

Answers

  • HI

     You have retrieve Status record and assign again to Statues variable which is of type Status table.

    It is like User Table contains status table. So the record is getting created twice. Instead of

         public Status statuses{get;set;} use  

         public int StatusIdFor{get;set;} and ForeignKey("StatusIdFor"). It will avoid recreation of record.

    Hope this helps

    Thanks

    Sowmiya

    Wednesday, October 16, 2013 11:49 AM

All replies

  • Hi Raghul

              I think the problem is 

    objUser.Statuses = objstatus;

              the property Statuses is of Status table type. So your table user referred the status table like below.

                
    class user
      {
         //some property
          Status statuses{get;set;} 
           //or
          List<Status> statuses{get;set;}
      }

    So while inserting user record, status value also getting inserted. Please share your context class. It helps for us to analyse the code.

    Thanks

    Sowmiya

                       

    Wednesday, October 16, 2013 10:56 AM
  • Hi,

    I have provided the details that you have asked for.

    I am using the example provided in the link

    http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

    This is my Context class

    public class BaseDBContext : DbContext
        {
            public BaseDBContext(string connString)
                : base(connString)
            {
            }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //configure model with fluent API
              
            }
            public DbSet<User> Users { get; set; }
            public DbSet<Status> Statuses { get; set; }
        }
    Below is my Entity, Here I have a base class called BaseEntity because this status field, created date, created by and Id  needs to be used in all the entities
     public class Status
        {
            [Key]
            public int Id { get; set; }
            public string InternalName { get; set; }
            public string StatusName { get; set; }
        }
    public class User : BaseEntity
        {
            public string UserName { get; set; }
            public string Category { get; set; }
        }
     public class BaseEntity
        {
            [Key]
            public int Id { get; set; }
            ForeignKey("Statuses")]
            public int Status_Id { get; set; }
            public Status Statuses { get; set; }
            public string CreatedBy { get; set; }
            public DateTime CreatedDate { get; set; }
        }
    Please help

    Regards, Raghul


    Wednesday, October 16, 2013 11:15 AM
  • HI

     You have retrieve Status record and assign again to Statues variable which is of type Status table.

    It is like User Table contains status table. So the record is getting created twice. Instead of

         public Status statuses{get;set;} use  

         public int StatusIdFor{get;set;} and ForeignKey("StatusIdFor"). It will avoid recreation of record.

    Hope this helps

    Thanks

    Sowmiya

    Wednesday, October 16, 2013 11:49 AM