我有那些模特
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; }
}
因此,每个艺术家都有来自同一张桌子的其他5个链接。当迁移生成数据库时,它就会产生结构。
SELECT [Id]
,[Name]
,[LastName]
FROM [dbo].[Artists]
SELECT [Id]
,[ArtistId]
,[Similar_Artist_Id]
FROM [dbo].[SimilarArtists]
所以,当我选择模型时,它会返回
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
问题是我如何才能进入“var similar”,而不仅仅是Similar_Artist_Id,还有同一个请求中的姓名和姓氏(没有提出Similar_Artist_Id的请求)
答案 0 :(得分:1)
var similarId = model.SimilarArtists.FirstOrDefault().Id;
var artiest = _db.Artists.Where(x.Id = similarId);
或只是:
similar.Artist.Name
或者,如果您希望能够拥有similar.ArtistName
等强类型属性,请创建一个[NotMapped]
getter属性。
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;
}
}
}
答案 1 :(得分:0)
你可以做到
var similar = _db.Artists.Where(x => x.Name == id)
.Select(a => a.SimilarArtists.FirstOrDefault())
.FirstOrDefault();
这为您提供了与谓词SimilarArtists
匹配的第一个Artists
的第一个x.Name == id
(及其所有属性)。