Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.net core: How to get the id of record in the table as the value for a column in another table?

Here is my service:

var news = new News()
{
    Views = request.Views,
    Title = request.Title, 
    Status = request.Status,
    Content = request.Content,
    CreatedDate = request.CreatedDate,
    UpdatedDate = request.UpdatedDate,
    CreatedBy = request.CreatedBy,
    UpdatedBy = request.UpdatedBy
};

_freedomContext.News.Add(news);
            
var image = new Image()
{
    IdObj = request.IdObj,
    Url = request.Url,
    Thumbnail = request.Thumbnail,
    Type = "news"
};
_freedomContext.Images.Add(image);

return await _freedomContext.SaveChangesAsync();

How to set IdObj is id of news when me create new record in News table?
Example: When me create news with id = 10, that parallel, IdObj of image =10.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to do following changes in your code:

var news = new News()
{
    Views = request.Views,
    Title = request.Title, 
    Status = request.Status,
    Content = request.Content,
    CreatedDate = request.CreatedDate,
    UpdatedDate = request.UpdatedDate,
    CreatedBy = request.CreatedBy,
    UpdatedBy = request.UpdatedBy
};

_freedomContext.News.Add(news);
//add below line so you can get news last saved id and you can use that id to save into image table.
await _freedomContext.SaveChangesAsync(); 
            
var image = new Image()
{
    IdObj = news.Id, //Changes
    Url = request.Url,
    Thumbnail = request.Thumbnail,
    Type = "news"
};
_freedomContext.Images.Add(image);

return await _freedomContext.SaveChangesAsync();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading