Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am building a project using .NET 7 and have three models that are related to each other in Models and I don't know how to implement them both in the create controller and view also with get method.

The three classes are "RealEstate" model, "RealEstateAgent" model and "RealEstateLocations" model. My question is... will I create the realestate together with the realestate models and is this the best way to go? Another guess if I am to create the location in its separate controller, how am I going to link it up in the database.
C#
<pre>  public class RealEstate
    {
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        public string Title { get; set; }

        [Required]
        [StringLength(255)]
        public string Address { get; set; }
        public DateTime DateEntered { get; set; }

        [Required]
        [DataType(DataType.Currency)]
        [Display(Name = "Price")]
        public decimal Price { get; set; }

        [Display(Name = "Number of Bedrooms")]
        public int Bedrooms { get; set; }

        [Display(Name = "Number of Bathrooms")]
        public int Bathrooms { get; set; }

        [Display(Name = "Square Footage")]
        public int SquareFootage { get; set; }

        [Display(Name = "Year Built")]
        public int YearBuilt { get; set; }

        [StringLength(5000)]
        [DataType(DataType.MultilineText)]
        public string Description { get; set; }

        [DataType(DataType.ImageUrl)]
        [Display(Name = "Image")]
        public string ImageUrl { get; set; }

        // Foreign key for the real estate agent 
        // associated with the property
        public int RealEstateAgentId { get; set; }

        // Navigation property for the real estate agent 
        // associated with the property
        public RealEstateAgent RealEstateAgent { get; set; }

        public ICollection<RealEstateLocation> 
               RealEstateLocation { get; set; }
    }

and the other model is below:
C#
public class RealEstateLocation
  {
      public int Id { get; set; }
      public string Address { get; set; }
      public string Country {get;set;}
      public string City { get;set;}
      public string State { get; set; }
      public string Phone { get; set; }
      public string? Email { get; set; }
      public string? Website { get; set; }

      public int RealEstateId { get; set; }
      public RealEstate RealEsate { get; set; }
  }

and the last:
C#
public class RealEstateAgent
   {
       public int Id { get; set; }

       [Required]
       [StringLength(500)]
       [Display(Name = "Full Name")]
       public string FullName { get; set; }

       [StringLength(50)]
       [Display(Name = "License Number")]
       public string LicenseNumber { get; set; }

       [DataType(DataType.PhoneNumber)]
       [Display(Name = "Phone Number")]
       public string PhoneNumber { get; set; }

       [DataType(DataType.EmailAddress)]
       [EmailAddress]
       public string Email { get; set; }

       [StringLength(5000)]
       [DataType(DataType.MultilineText)]
       public string Description { get; set; }

       [DataType(DataType.ImageUrl)]
       [Display(Name = "Image")]
       public string ImageUrl { get; set; }
       [Display(Name = "Years of Experience")]
       public int YearsOfExpereince { get; set; }
       [Display(Name = "Office Address")]
       public string OfficeLocation { get; set; }
   }

I was doing the create method in RealEstate controller, but I don't know how to implement the RealEstate create in it and also the location.

Please help! Thanks!

What I have tried:

C#
public IActionResult GetRealestate(int rId)
        {
            var realestateDetails = from realestatei in _dbContext.RealEstates
                                    where realestatei.Id == rId
                                    select new
                                    {
                                        Id = realestatei.Id,
                                        Title = realestatei.Title,
                                        Address = realestatei.Address,
                                        Price = realestatei.Price,
                                        Badrooms = realestatei.Bedrooms,
                                        Bathrooms = realestatei.Bathrooms,
                                        SquareFootage = 
                                              realestatei.SquareFootage,
                                        YearBuilt = realestatei.YearBuilt,
                                        Description = realestatei.Description,
                                        ImageUrl = realestatei.ImageUrl,
                                        RestaurantLocation = 
                                        realestatei.RealEstateLocation.Select
                                        (r => new
                                        {
                                            Id = r.Id,
                                            Address = r.Address,
                                            Country = r.Country,
                                            City = r.City,
                                            Phone = r.Phone,
                                            State = r.State,
                                            Email = r.Email,
                                            Website = r.Website,
                                        }),
                                    };
            var realestateDetailsViewModel = 
                realestateDetails.SingleOrDefault();

            if (realestateDetailsViewModel == null)
            {
                return NotFound(); // Handle the case where 
                                   // the hotel is not found
            }

            return Ok(realestateDetailsViewModel);
        }
Posted
Updated 12-Sep-23 9:18am
v2

1 solution

There is a bit more to a one-to-many relationship with Entity Framework:
1. Configure: Configure One-to-Many Relationships using Fluent API in Entity Framework Core[^]
2. Query: Querying in Entity Framework Core[^]

For #2, the query should look something like (not tested):
C#
var realestateDetails = realestateDetails
                           .Where(rd => rd.Id== rId)
                           .Include(rd => rd.RealEstateLocation)
                           .FirstOrDefault();

or
C#
var realestateDetails = (from rd in dbContext.RealestateDetails
                         where rd.Id == rId
                         select rd)
                        .Include(rd => rd.RealEstateLocation)
                        .FirstOrDefault();

You can refine the query with a Select and only pick the properties/table columns that you require.

NOTE: The above links are to a tutorial website that has a lot more information in an easy-to-read format that you can benefit from.

UPDATE

The links above are to an Entity Framework tutorial website[^]. Their information is very good for what you need. They have a Resources[^] page and on that page is a link to their code used on the website, so you can download, run, and learn by example from their code: GitHub - entityframeworktutorial/EF6-Code-First-Demo: Entity Framework 6 Code-First Demo Project[^].

Regarding database table structure and normalization, here is a brief article explaining the process: Database normalization description - Microsoft 365 Apps | Microsoft Learn[^]

Take the time to read the content and play with the sample code to learn. Then you are ready to tackle your project.

If video learning is more your thing, try these videos:
* Getting Started with Entity Framework Core [1 of 5] | Entity Framework Core for Beginners - YouTube[^]
* 5 part series: Getting Started with Entity Framework Core [1 of 5] | Entity Framework Core for Beginners - YouTube[^]
 
Share this answer
 
v4
Comments
Carol Sheridan 9-Sep-23 5:04am    
i saw that part online but what about the create method. what am i saving? is it just the realesate and all in their respective controllers?
Graeme_Grant 9-Sep-23 5:49am    
The key part of the query is that you need to Include the children for the data to be retrieved. The Create is generating the relationship between the tables. It's all in the links provided.
Carol Sheridan 9-Sep-23 7:14am    
OK i will check and come back if there's anything i don't understand
Carol Sheridan 9-Sep-23 18:50pm    
id does not adress the issue i am searching for.. i have configure the relationship in models but how to write my create and put method is the problem the link just address the get method which is the "include" using linq
Graeme_Grant 9-Sep-23 19:48pm    
The first link answers that question. You need to map the DTO (Data Transfer classes or your classes in this case) relationships for Entity Framework. A required step. Once done, you can then use Include to to do SQL "join".

I've updated my answer above with more information that will not only help you with this problem, but much much more. Please take the time to learn and understand before working further on your project. The upfront time investment will be worth your while.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900