Write A LINQ query, How to update(modify) child table data when parent table is inserted [Resolved]

Posted by Kasani007 under LINQ on 11/11/2016 | Points: 10 | Views : 592 | Status : [Member] | Replies : 2
Write A LINQ query, How to update(modify) child table data when parent table is inserted




Responses

Posted by: Rajnilari2015 on: 11/16/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Consider we have a parent and child as under

public class Parent
{
public Parent()
{
this.Children = new List<Child>();
}

public int Id { get; set; }

public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
public int Id { get; set; }

public int ParentId { get; set; }

public string Data { get; set; }
}

The below program will do so

public void UpsertChildParent(ParentModel model)
{
var parent = _dbContext.Parents
.Where(p => p.Id == model.Id)
.Include(p => p.Children)
.SingleOrDefault();

if (parent != null)
{
// Update parent
_dbContext.Entry(parent).CurrentValues.SetValues(model);

// Delete children
foreach (var existingChild in parent.Children.ToList())
{
if (!model.Children.Any(c => c.Id == existingChild.Id))
_dbContext.Children.Remove(existingChild);
}

// Update and Insert children
foreach (var childModel in model.Children)
{
var existingChild = parent.Children
.Where(c => c.Id == childModel.Id)
.SingleOrDefault();

if (existingChild != null)
// Update child
_dbContext.Entry(existingChild).CurrentValues.SetValues(childModel);
else
{
// Insert child
var newChild = new Child
{
Data = childModel.Data,
//...
};
parent.Children.Add(newChild);
}
}

_dbContext.SaveChanges();
}
}

Hope this helps

--
Thanks & Regards,
RNA Team

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Manicse on: 11/17/2016 [Member] Bronze | Points: 25

Up
0
Down
Hi,

Is that you mean like inserting the parent table into child table?
I have tried once to do so. Kindly check whether you are expecting something like this.

Suppose you have table like below.

create table parent(id int primary key,name varchar(40),class varchar(40))


create table child(id int foreign key references parent(id), age int,village varchar(50))

Now you want to add the Parent value in the child.

DECLARE @pid INT --parent id, where id is identity for parent table


INSERT INTO parent ([name], [class])
VALUES('Name', 'last')

SELECT @pid = @@IDENTITY

INSERT INTO child(pid, age, village)
VALUES(@pid, 21, 'Village')


Mani.R

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response