Getting error while inserting department foreign key in Employee table - entity-framework

I am beginner to Entity Framework. I want to insert employees along with department as foreign key, but I am getting the following error while adding records:
The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Employees_dbo.Departments_DepartmentId\". The conflict occurred in database \"EmpDB\", table \"dbo.Departments\", column 'Id'.\r\nThe statement has been terminated.
Department class:
namespace DbSet_Exmp.Models
{
public class Department
{
public int Id { get; set; }
public string DeptName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
}
Employee class:
namespace DbSet_Exmp.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Contact { get; set; }
public int Salary { get; set; }
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
}
DbContext class:
public class EmpDbContext:DbContext
{
public EmpDbContext() : base("name=myDBConString")
{
Database.SetInitializer(new DBInitializer());
}
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> employees { get; set; }
}
Index action:
public ActionResult Index()
{
using (var context = new EmpDbContext())
{
Employee objEmp = new Employee() { Name = "Swara", Contact = "123569", Salary = 15000, DepartmentId = 2 };
context.employees.Add(objEmp);
context.SaveChanges();
}
return View();
}

Usually this error thrown when you are assigning a value to the ForeignKey but there is no such data with that value in ForeignKey table.
In your case there is no Department with Id = 2 in your Department table . So you can check it in your Departement table.

Related

EF Core 2.1 'UNIQUE constraint failed: People.ReferredById'

My Data Model
Table("People")]
public abstract class Person
{
public long Id { get; set; }
public string Name { get; set; }
[ForeignKey("ReferredBy")]
public long? ReferredById { get; set; }
public User ReferredBy { get; set; }
}
public class User : Person
{
public string UserName { get; set; }
}
public class Student : Person
{
public string RollNo { get; set; }
}
Fluent API to set null on delete
modelBuilder.Entity<Person>()
.HasOne(t => t.ReferredBy)
.WithOne()
.OnDelete(DeleteBehavior.SetNull);
Now when i try to insert a row with same ReferredByit throws an unique constraint error. Please help me with this.

update foreign key using entity framework

i am trying to update foreign key in a table named(Friendship).The foreign key is of the table named(FriendshipStatus) the problem is that all the values are updated except the foreign key. I m using code first approach.
Friendship Class
public class Friendship
{
public int Id { get; set; }
public User UserOne { get; set; }
public User UserTwo { get; set; }
public FriendshipStatus Status { get; set; }
public User ReqSB { get; set; }
public RelationType RelationType { get; set; }
public Relationship Relationship { get; set; }
public DateTime FriendshipDate { get; set; }
}
FriendshipStatus class
public class FriendshipStatus
{
public int Id { get; set; }
public string Name { get; set; }
}
Here is the code for update
using (context)
{
Friendship f = getFrienshipRecord(u1, u2); // get single record from db which is to be updated
if (f != null)
{
Friendship ff = new Friendship();
ff.Status = new FriendshipStatus() { Id = 2}; //actually wants to update this this field
ff.Id = f.Id;
ff.FriendshipDate = DateTime.Now;
context.Entry(ff).State = EntityState.Modified;
context.SaveChanges();
}
}
The above code changes datetime but it does not change foreign key.
This is the technique I use for updates that include a child. First, I like to expose the Foreign Key as part of the parent. If you name it FriendshipStatusId, EF will make the association automatically or you can add an annotation or fluent code if preferred:
public class Friendship
{
public int Id { get; set; }
public User UserOne { get; set; }
public User UserTwo { get; set; }
public int? FriendshipStatusId { get; set; } // optional FK
public FriendshipStatus Status { get; set; }
public User ReqSB { get; set; }
public RelationType RelationType { get; set; }
public Relationship Relationship { get; set; }
public DateTime FriendshipDate { get; set; }
}
Now you can do your update by simply fetching the entity (which puts it under tracking) and updating the FK:
using (context)
{
Friendship f = getFrienshipRecord(u1, u2); // get single record from db which is to be updated
if (f != null)
{
f.FriendshipDate = DateTime.Now;
f.FriendshipStatusId = 2;
context.SaveChanges();
}
}
Note that if you add the FK you may need to do a migration or regenerate your database because the EF default might be something like FriendshipStatus_Id.

Merge Key constraint with Entityframework

I am a .NEt student trying to build a simple pizza webbshop. I am using Entityframework to build the database. The errormessage I get is this:
The MERGE statement conflicted with the FOREIGN KEY constraint "FK_Products_Categories_CategoryID". The conflict occurred in database "TomasosPizzeria", table "dbo.Categories", column 'CategoryID'.
The statement has been terminated.
I have googled and tried to solve this pne alone by renaming the properties back and forth. Here are my classes:
public class Product
{
public int ID { get; set; }
public string ProductName { get; set; }
public int ProductPrice { get; set; }
public string Ingridients { get; set; }
//--
public List<OrderDetail> OrderDetails { get; set; }
[ForeignKey("Categories")]
public int CategoryID { get; set; }
public virtual Category Categories { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
List<Product> Products { get; set; }
}
I am using a DbInitializer to set som test values. I have had problems giving the product object a category with the corresponding value.
var categories = new Category[]
{
new Category{CategoryName="Pizza"},
new Category{CategoryName="Pasta"},
new Category{CategoryName="Sallad"},
};
var products = new Product[]
{
new Product{ProductName="Äcklig Calzone", Ingridients="Gamla tomater, möglig ost, trötta oliver, Unken skinka", ProductPrice=150},
new Product{ProductName="Italiensk skit", Ingridients="Proscutti, halvfärdig mozzarella, trötta oliver, skämd vattnig proscutti", ProductPrice=250},
new Product{ProductName="La bussola", Ingridients="Äckliga tomater, giftiga räkor, levande musslor, rutten skinka",CategoryID = 2,<--Here-- ProductPrice = 105 }
};
foreach (Product s in products)
{
context.Products.Add(s);
}
context.SaveChanges();
I am thankful for all the help I get. Please tell me if you wish to see any more of my code.
Solved it by giving CategoryID to the two other products.

how to (INSERT) data in this table in entity framework code first?

-------------------
using EF 6
-------------------
I have 3 table :
1) Users
public class Users
{
[Key,Required, MaxLength(50)]
public string UserName { get; set; }
[Required, MaxLength(128)]
public string Email { get; set; }
[Required, MaxLength(128)]
public string Password { get; set; }
}
2) Roles
public class Roles
{
[Key,Required, MaxLength(50)]
public string RoleName { get; set; }
[MaxLength(50)]
public string ApplicationName { get; set; }
}
3) UsersInRoles //My Problem.
public class UsersInRoles
{
[Key]
public int id { get; set; }
[ForeignKey("Users"), Required]
public string FKUserName { get; set; }
public virtual Users Users { get; set; }
[ForeignKey("Roles"), Required]
public string FKRoleName { get; set; }
public virtual Roles Roles { get; set; }
}
Now my question is how to insert record in UsersInRoles table ???
i use following code but don't insert any data in table!
even don't show any errors!
List<UsersInRoles> BUsersInRoles = new List<UsersInRoles>
{
new UsersInRoles { FKUserName="User1", FKRoleName="Role1"},
new UsersInRoles { FKUserName="User2", FKRoleName="Role2"}
};
foreach (UsersInRoles BIR in BUsersInRoles)
{
db.UsersInRoles.Add(BIR);
}
db.SaveChanges();
Thanks.
Update:
i have found a error :
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.UsersInRoles_dbo.Roles_FKRoleName". The conflict occurred in
database "AriyaRad", table "dbo.Roles", column 'RoleName'. The
statement has been terminated.
I solve my problem!
The reason was i define single string value for Foreign Key but try to insert list of string value!
db.UsersInRoles.Add(new UsersInRoles {FKUserName="User1",
FKRoleName="Role1", ApplicationName="PSCMS"});
db.SaveChanges();

Storing data in two tables at a time in Entity Framework

I have three tables
Products { pid, pname, price }
Orders { oid, odate }
OrderDetails { odid, oid, pid, qty, total }
I've a form which upon submission passes an array of OrderDetails which I want to store in database. But the tragedy here is I want to store current date in Order table at the same time. Now my Order table is getting populated with odate but nothing is getting inserted in my orderdetails table. And I'm using web api and the array is fetched correctly in controller. I guess this line
aOrder.AllOrders.Add(od);
in the controller has to be replaced with somethting else.
Order.cs
public class Order
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int oid { get; set; }
[DataType(DataType.DateTime)]
public DateTime odate { get; set; }
public virtual List<OrderDetail> AllOrders { get; set; }
public Order()
{
AllOrders = new List<OrderDetail>();
}
}
OrderDetail.cs
public class OrderDetail
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int odid { get; set; }
public int oid { get; set; }
public virtual Order order { get; set; }
public int pid { get; set; }
public int qty { get; set; }
public int total { get; set; }
public virtual Product Aproduct { get; set; }
public OrderDetail()
{
Aproduct = new Product();
}
}
OrderDetailsController.cs
private static readonly IOrderDetailRepository _orders = new OrderDetailRepository();
public Order Post(List<OrderDetail> orderDetails)
{
Order aOrder = new Order();
foreach(OrderDetail orderDetail in orderDetails)
{
OrderDetail od = new OrderDetail();
od.oid = orderDetail.oid;
od.pid = orderDetail.pid;
od.qty = orderDetail.qty;
od.total = orderDetail.total;
aOrder.AllOrders.Add(od);
}
aOrder.odate = DateTime.Now;
return _orders.Add(aOrder);
}
OrderDetailRepository.cs
public Order Add(Order order)
{
_db.Orders.Add(order);
_db.SaveChanges();
return order;
}
Can you try specifying a foreign key for OrderDetails:
public class OrderDetail
{
[ForeignKey("Order")]
public int oid { get; set; } //I'm guessing this is Order's PK