Search code examples
asp.net-core-mvcforeign-keysasp.net-core-7.0

ASP.Net Core 7 Entity Relationships and Viewing Data


I'm using ASP.NET Core 7 and I have models Project and DataListItem.

I need to create a relationship between the two so that I can display the value in the view of the DataListItem (DataListValue).

The Project class may have multiple references to the DataListItem model.

public class Project
{
    ProjectId
    [Display(Name = "Project Status")]
    [Required]

    [ForeignKey("DataListItem")]
    public int Project_Status { get; set; }
 }

I have a model called DataListItem

public class DataListItem
{
    [Key] 
    public int DataListId { get; set; }
    [Display(Name = "Value")]
    public string DataListValue { get; set; } = string.Empty;
    [Display(Name = "Default")]
 }

I want to create a relationship between the two such that in my view I can add something like this

@Html.DisplayFor(model => project.Project_Status.DataListValue)

Have tried multiple ways and I am struggling.


Solution

  • From your question, you seems to wanna create a relationship between Project and DataListItem, Then in the view show the property in DataListItem which correspond to the current Project. Because I don't know what kind of relationship you want to create, So here i create a one-to-many relationship as example.

    public class Project
        {
            public int ProjectId { get; set; }
    
            [Display(Name = "Project Status")]
            [Required]
            public int Project_StatusId { get; set; }
    
            [Display(Name = "Project Status")]
            [ForeignKey("Project_StatusId")]
            public DataListItem Project_Status { get; set; }
    
            public string propertyA { get; set; }
        }
    
    public class DataListItem
        {
            [Key]
            public int DataListId { get; set; }
    
            [Display(Name = "Value")]
            public string DataListValue { get; set; } = string.Empty;
    
            public ICollection<Project> Projects { get; set; }
        }
    

    Now the table construct in database will be like:

    enter image description here

    enter image description here

    If I want to show DataListValue in current view, I can use:

    public IActionResult Privacy()
            {
                var value = _context.projects.Where(x => x.ProjectId == 1).Include(x => x.Project_Status).FirstOrDefault();
                return View(value);
            }
    

    View

    @model Project
    
    @Html.DisplayFor(model => Model.Project_Status.DataListValue)
    
    @Html.DisplayFor(model => Model.propertyA)
    

    enter image description here

    Hope this demo can help you solve your issue.