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

Time:12-28

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.

CodePudding user response:

Normally you should have classes with properties that link the instances together:

class News { 
  public ICollection<Image> Images {get;set;} = new()(
  ...
class Image {
  public News News {get;set;}
}

In this case one News has many Image

You can just build the entire related graph of objects and ask EF to save it:

var n = new News { ... }
n.Images.Add(new Image {...});

context.News.Add(n);
context.SaveChanges();

EF will be able to see the new Image and know which News it is related to because it is stored in the n.Images list. When it saves the data, it will automatically get the IDs and make the linkages. You don't have to do all this manually, saving one thing at a time, pulling its ID out, setting it somewhere else, saving again..

CodePudding user response:

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();
  • Related