0

I have those models

class Artist
{
    public int Id { get; set; }
    [StringLength(500)]
    public string Name { get; set; }
    [StringLength(50)]
    public string LastName { get; set; }

    public virtual ICollection<SimilarArtist> SimilarArtists { get; set; }   
}

class SimilarArtist
{
    public int Id { get; set; }
    public int ArtistId { get; set; }
    [ForeignKey("ArtistId")]
    public Artist Artist { get; set; }
    public int Similar_Artist_Id { get; set; }
}

So each artist have links to other 5 from the same table. When the migration generate database it made that stracture.

SELECT [Id]
      ,[Name]
      ,[LastName]
  FROM [dbo].[Artists]

SELECT [Id]
      ,[ArtistId]
      ,[Similar_Artist_Id]
  FROM [dbo].[SimilarArtists]

So when I do select the model it return this

var similar = _db.Artists.FirstOrDefault(x => x.Name == id).SimilarArtists.FirstOrDefault();

//similar.ArtistId 
//similar.Id
//similar.Similar_Artist_Id
//similar.Artist //the object which return main artist 

The question is how I can get in "var similar" not just Similar_Artist_Id but also name and lastname in the same request (without making requests by Similar_Artist_Id)

2 Answers 2

1
var similarId = model.SimilarArtists.FirstOrDefault().Id;
var artiest = _db.Artists.Where(x.Id = similarId);

or just:

similar.Artist.Name

Or if you want to be able to have strongly-type property such as similar.ArtistName, create a [NotMapped] getter property.

class SimilarArtist
{
    public int Id { get; set; }
    public int ArtistId { get; set; }
    [ForeignKey("ArtistId")]
    public Artist Artist { get; set; }
    public int Similar_Artist_Id { get; set; }
    [NotMapped]
    public string ArtistName 
    {
       get 
       {
           return this.Artist.Name;            
       }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

1) it is more requests to database. sure i can do it but it is not a point 2) similar.Artist.Name return main artist name and it is the same for each 5
Artist object based on [ForeignKey("ArtistId")] and it return info which I alredy have -> main artist, but I need object based on Similar_Artist_Id. And it is the question.
0

You can do

var similar = _db.Artists.Where(x => x.Name == id)
              .Select(a => a.SimilarArtists.FirstOrDefault())
              .FirstOrDefault();

This gives you the first SimilarArtists (with all of its properties) of the first Artists matching the predicate x.Name == id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.