I have two different tables one of them is Titles other one is Categories. Titles have 4 columns as Name, OWS, TWS, and CategoryId Categories have 3 columns as Id, Name, ParentName.
I want to show the Category Name on the Titles table instead of CategoryId.
I search and I see some solutions by using Foreign Key. CategoryId is not defined as FK. But I cannot change the tables from db because of authentication issues.
First of all, I declared virtual categories in Titles Model
public class Titles
{
public Guid Id { get; set; }
public string Name { get; set; }
public string OWS { get; set; }
public string TWS { get; set; }
public Guid CategoryId { get; set; }
public virtual Categories Category { get; set; }
}
Then I work with TitlesController Index() method. When I write CategoryId=m.CategoryId, I see the categoryIds on the Titles Table. And I think that if I use Category.Name instead of CategoryId, I can see the CategoryName in the Titles Table. In this case I get convert type error as string to system guid.
public async Task<IActionResult> Index()
{
var titles = _context.Titles
.Select(m => new Titles()
{
//Id=m.Id,
Name = m.Name,
OWS = m.OWS,
TWS = m.TWS,
CategoryId=m.Category.Name
});
return View(await titles.ToListAsync());
}
I think, converting CategoryName to Guid is not make sense and also converting CategoryId to string can be ruined the other parts of the project.
As a result, how can I show the category name instead of categoryId without using FK?
you can add a property in your model as NotMapped like below
public class Titles
{
public Guid Id { get; set; }
public string Name { get; set; }
public string OWS { get; set; }
public string TWS { get; set; }
public Guid CategoryId { get; set; }
[NotMapped]
public string CategoryName { get; set; }
public virtual Categories Category { get; set; }
}
and for logic as below
var titles = _context.Titles.Include(t=>t.Category)
.Select(m => new Titles()
{
//Id=m.Id,
Name = m.Name,
OWS = m.OWS,
TWS = m.TWS,
CategoryName=m.Category.Name
});
also you can make a separate Dto instead of Not Mapped property and use it direct as model of your view
you must use NotMapped attribute
public class Titles
{
public Guid Id { get; set; }
public string Name { get; set; }
public string OWS { get; set; }
public string TWS { get; set; }
public Guid CategoryId { get; set; }
[NotMapped]
public string CategoryName
public virtual Categories Category { get; set; }
}
and
var titles = _context.Titles.Select(m => new Titles()
{
Name = m.Name,
OWS = m.OWS,
TWS = m.TWS,
CategoryName=m.Category.Name
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.