Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - MVC 5 Code First scaffolding with simple relationship

I'm doing some experimental programming to get caught up with ASP MVC.

I created a project for buildings containing rooms. A very simple one to many relationship. I am trying to get scaffolding to work, and from older MVC examples it looks like this should just work. However, the BuildingId field in Rooms isn't mapping to the Building model - no select list in the view.

My models are:

namespace BuildingManagement.Models
{
    public class Building 
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }
        public string Address { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        public string PostalCode { get; set; }

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

        [Display(Name = "Contact")]
        [Required]
        public string ContactName { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Room> Rooms { get; set; }      

    }
}

and

namespace BuildingManagement.Models
{
    public class Room
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }
        public string Type { get; set; }
        public int BuildingId { get; set; }        
    }
 }

I generated the controller with views using Entity Framework, it created the forms but not with the expected Building select list in the Room edit view. It displays an integer input field instead.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should change this:

public class Room
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
    public string Type { get; set; }
    public int BuildingId { get; set; }        
}

to

public class Room
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
    public string Type { get; set; }

    [ForeignKey("ContainingBuilding")]
    public int BuildingId { get; set; }      

    public virtual Building ContainingBuilding{ get; set;}
}

This way the scaffolding will generate a select list for the building.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...