Upgraded to Entity Framework 6 Related entities not being inserted - c#

I upgraded From EF 4 to EF6 in my solution. Now my related entities are not getting inserted. How do I add records to the entity with foreign key relationship from the original enity
var _bp = new BP(); //BP is an entity
workflowList.ForEach(wf =>
{
var wflow = new Workflow
{
currentstep = CustomConvert.ToIntNullable(wf.currentstep),
desc = wf.desc,
name = wf.name,
wfId = wf.id,
BP = _bp,
IsActive = true
};
});
db.BP.AddObject(_bp);
db.SaveChanges();
The code above would add a record in BP table and add multiple records in the workflow table in EF 4 but in EF 6 it does not add any record to the Worflow table. How do I accomplish the same in EF6

Related

Delete unattached many-to-many self-referencing relationship

What's the best way to delete an unattached entity which has self-referencing relationships?
My example is pretty simple, just a People class with a List<People> Friends property:
Edit: I don't define an extra relationship object but I force Entity Framework to use an extra table:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<People>()
.HasMany(people => people.Friends)
.WithMany()
.Map(configuration =>
{
configuration
.MapLeftKey("From_PeopleId")
.MapRightKey("To_PeopleId")
.ToTable("Friendships");
});
}
The schema:
Id Name
== ======
1 Martha
2 Martin
3 Jim
From_PeopleId To_PeopleId
============= ===========
1 2
1 3
3 2
And how I'd like to delete old Jimmy Boy:
using (var context = new FriendsDbContext())
{
var people = context.Peoples.Find(3);
context.Peoples.Remove(people);
context.SaveChanges();
}
SqlException #1:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Friendships_dbo.People_From_PeopleId".
The conflict occurred in database "FriendsDb", table "dbo.Friendships", column 'From_PeopleId'.
My second approach to get rid of old Jimmy boy including his relations:
using (var context = new FriendsDbContext())
{
var people = context.Peoples
.Include(p=>p.Friends)
.Single(p=>p.Id==3);
context.Peoples.Remove(people);
context.SaveChanges();
}
SqlException #2:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Friendships_dbo.People_To_PeopleId".
The conflict occurred in database "FriendsDb", table "dbo.Friendships", column 'To_PeopleId'.
I know why the SqlExceptions occured (SQL Server is not capable to provide cascade delete allowing the deletion of all relations pointing from and to old Jimmy boy at once). So my question is: How could I do it with the help of Entity Framework easily? Easily like DELETE Friendships WHERE From_PeopleId=3 OR To_PeopleId=3.
Try to delete the relations before or in the meantime
using (var context = new FriendsDbContext())
{
var friendships = context.Friendships.Where(x => x.From_PeopleId == 3 || x.To_PeopleId == 3).ToList();
context.RemoveRange(friendships);
var people = context.Peoples.Find(3);
context.Peoples.Remove(people);
context.SaveChanges();
}

C# - Entity Framework inserting

I have two tables Category and Product and I would like to insert products into categories. The table relation between these tables is one to zeor or one.
Category table:
CID : integer,
CategoryName : varchar,
Product table:
CID: integer, // foreign key to category table.
ProductName: varchar,
UnitsInstock: integer,
How can I write a simple query for inserting a product into the ProductTable? How do I handle the foriegn key situation? If the categoryid does not exists then the product should not be inserted.
I would realy appreciate any kinds of help.
One approach could be this one:
int categoryIdOfNewProduct = 123;
using (var context = new MyContext())
{
bool categoryExists = context.Categories
.Any(c => c.Id == categoryIdOfNewProduct);
if (categoryExists)
{
var newProduct = new Product
{
Name = "New Product",
CategoryId = categoryIdOfNewProduct,
// other properties
};
context.Products.Add(newProduct); // EF 4.1
context.SaveChanges();
}
else
{
//Perhaps some message to user that category doesn't exist? Or Log entry?
}
}
It assumes that you have a foreign key property CategoryId on your Product entity. If you don't have one please specify more details.
Normally a category to product would be many to one, but I would suggest studying the basics of Linq to Sql first:
http://msdn.microsoft.com/en-us/library/bb425822.aspx
Linq to Sql 101
Learn the Entity Framework

Table with 2 foreign keys entity framework

I have a table which consists of 2 foreign keys. And those are only elements of the table. The table is meant to create association between 2 other tables. For example: The table is Users_Products, and the only 2 columns are UserId and ProductID, both foreign keys. When I generated the EF object from database it didn't create Users_Products object, it only automatically created navigation properties. Now how can I insert data in my Users_Products table using EF?
You can get some user object and add product into its navigation property.
User user = context.Users.Where(u => u.Id == 1);
Product product = context.Products.Where(p => p.Id == 1);
user.Products.Add(product);
context.SaveChanges();
For code examples that show how to work with many-to-many relationships in EF see the Working with Many-to-Many Relationships section in
The Entity Framework 4.0 and ASP.NET – Getting Started Part 5.
That is EF 4.0 / Database First; for an example using the DbContext API, see Adding Course Assignments to the Instructor Edit Page in Updating Related Data with the Entity Framework in an ASP.NET MVC Application (6 of 10).
using ( var ctx = new ...)
{
var user = new User();
var product = new Product();
user.Products.Add(product);
ctx.Users.AddObject(user);
ctx.SaveChanges();
}
If you want to create relation (insert record to User_Products table) you just need to use navigation property either on User or Product:
user.Products.Add(product);
or
product.Users.Add(user);
That means you must have navigation property on at least one side to be able to create the relation. If you have loaded entities from the current contest you can use the approach described by #Pavel.
If you don't have loaded entities or if you don't want to do two queries to the database just to make a relation you can use this workaround:
// Make dummy objects for records existing in your database
var user = new User() { Id = 1 };
var product = new Product() { Id = 1 };
// Ensure that your context knows instances and does not track them as new or modified
context.Users.Attach(user);
context.Products.Attach(product);
// Again make relation and save changes
user.Products.Add(product);
ctx.SaveChanges();

Insert foreign key reference in entity frameowrk 3.5

I have 3 tables
a. Employee (EmpID (pk), EmpName)
b. Department (DepID (pk), DepName)
c. EmployeeDepartmentMapping (ID (pk), EmpID(fk), DepID(fk))
When I am inserting new employee, I want to insert correspoding Emp-Dep mappings in the EmployeeDepartmentMapping table using entity framework 3.5. Can any body help/tell me how to insert many-many relationships using entity framework in database?
Thanks,
Ashwani
Employee emp = new Employee();
EmployeeDepartmentMapping edm = new EmployeeDepartmentMapping();
edm.Emp = emp;
if u know the dept id.
then
edm.Dept = _ent.Department.where(i => i.deptId == dept_id).first();
_ent.AddToEmplyee(emp);
_ent.AddToEmployeeDepartmentMapping(edm);
emp.<RolesEmpMapTable>Refernce.Load();
emp.<RolesEmpMapTable>.Role = _ent.Roles.where(i=>i.roleId == role_id).first();

Why would Entity Framework be able to retrieve entities but not save/update/delete them?

I have a WPF app with a local .MDF file on which I created an Entity Framework class model.
Retrieving entities from the database works fine:
//get entities
using (var context = new TestDataEntities1())
{
var customers = from c in context.Customers
select c;
foreach (var customer in customers)
{
TheCustomers.Add(customer);
}
}
However, updating and adding and deleting* do not. There is **no error, the debugger steps right through, no messages in Output, but the data in the database table remains unchanged.
//update entity
using (var context = new TestDataEntities1())
{
var customer = (from c in context.Customers
where c.Id == 1
select c).FirstOrDefault();
customer.FirstName = DateTime.Now.ToString();
int num = context.SaveChanges(); //returns 1, table unchanged
}
//add entity
using (var context = new TestDataEntities1())
{
var customer = new Models.Customers();
customer.FirstName = "Ned";
customer.LastName = "Newton";
context.AddToCustomers(customer);
int num = context.SaveChanges(); //returns 1, table unchanged
}
//delete entity
using (var context = new TestDataEntities1())
{
var customer = (from c in context.Customers
where c.Id == 2
select c).FirstOrDefault();
context.Detach(customer); // table unchanged
}
What do I have to do to get Entity Framework to also update and add entities to the database table?
First, SaveChanges does not guarantee an update. It returns the # of rows changed. So check the return value. If it's 0, then the EF doesn't think it made an update. If it's > 0 then it does.
Second, you should profile SQL to see what the EF is sending.
If the result of SaveChanges is 0, then the cause is almost certainly that the EF doesn't think anything in the context is modified. Why that would be depends upon how your changes are tracked. Your code above looks correct for insert, but for update the ApplyPropertyChanges is superfluous and should be removed.
If the EF is sending SQL but the DB is doing nothing with it, you should examine the SQL for a fix.

Categories