TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
osyris zosar
NA
289
27k
How to add data into 2 different tables with EnityFramework
Apr 4 2021 6:46 AM
I would like to add new data rows with entityframworks to 2 different tables
I dont know how to do this problably because both tables Have the same Key Name
public
async Task
Create([Bind(
"ProductId,ProductTitle,ProductDiscription,Price,quantity,HeaderImage,MultipleImages"
)] ProductWithImages productWithImages)
{
Guid NewProductId = Guid.NewGuid();
string
uploadPath = Path.Combine(_webhostenv.WebRootPath,
"Images2"
);
if
(ModelState.IsValid)
{
string
FileName = Guid.NewGuid().ToString() + productWithImages.HeaderImage.FileName;
string
FilePath = Path.Combine(uploadPath, FileName);
productWithImages.HeaderImage.CopyTo(
new
FileStream(FilePath, FileMode.Create));
ProductWithImagesDb newproduct =
new
ProductWithImagesDb()
{
ProductId = NewProductId,
ProductTitle = productWithImages.ProductTitle,
ProductDiscription = productWithImages.ProductDiscription,
Price = productWithImages.Price,
quantity = productWithImages.quantity,
HeaderImage = FileName,
};
_context.ProductWithImagesDb.Add(newproduct);
await _context.SaveChangesAsync();
// succesfully adds the newproduct data into the ProductWithImagesDb table
//---------------------------------------------------------------------------
if
(productWithImages.MultipleImages !=
null
)
{
int
imgorder = 0;
foreach
(IFormFile photo
in
productWithImages.MultipleImages)
{
imgorder++;
string
filename = Path.GetRandomFileName() +
"_"
+ photo.FileName;
string
filepath = Path.Combine(uploadPath, filename);
await photo.CopyToAsync(
new
FileStream(filepath, FileMode.Create));
var productImages =
new
ProductImages();
productImages.ProductId = NewProductId;
productImages.ImagePath = filename;
productImages.ImageOrder = imgorder;
_context.ProductImages.Add(productImages);
await _context.SaveChangesAsync();
}
}
//once the productWithImages.MultipleImages is used
//it crashes because it is a different table but uses the same key
(ProductId)
//-------------------------------------------------------------------------------------
return
RedirectToAction(nameof(Index));
}
return
View();
}
I know that once entityFramework sees the _context.add it tracks to that database table
Maybe I can remove the tracking so it can look for a new database Table
I dont know to do that or if that would even be a good idea
Reply
Answers (
3
)
How to save table's multiple rows in database
Update GridView.