安装更新 MvcScaffolding
Update-Package MvcScaffolding
Install-Package MvcScaffolding
定义一个Team与Player一对多的关系
创建一个小组实体类
public class Team { public int TeamId { get; set; } [Required] public string Name { get; set; } public string City { get; set; } public DateTime Founded { get; set; } }
加入一个球员与小组的关系
public class Player { public int PlayerId { get; set; } public string Name { get; set; } // Having a property called <entity>Id defines a relationship public int TeamId { get; set; } }
通过http://....../Team创建几个小组
通过http://..../Playser建立几个球员,创建时选择球队。
通过以上方式创建的代码,不能查看球队里边球员,原因是Team与Player没有建立关系
更新Player代码如下,告诉player属于球队
public class Player { public int PlayerId { get; set; } public string Name { get; set; } public int TeamId { get; set; } public virtual Team Team { get; set; } // This is new }
virtual使用该属性实现延迟加载,相关的实体内容根据需要被提取
Team中有球员的属性
public class Team { public int TeamId { get; set; } [Required] public string Name { get; set; } public string City { get; set; } public DateTime Founded { get; set; } public virtual ICollection<player> Players { get; set; } // This is new }
通过如下命令创建
Scaffold Controller Team -Force
Scaffold Controller Player -Force
预先加载和SELECT N +1
// This is on PlayersController public ViewResult Index() { return View(context.Players.Include(player => player.Team).ToList()); }
仓储模式
Scaffold Controller Team -Repository -Force
Scaffold Controller Player -Repository -Force
public PlayersController(ITeamRepository teamRepository, IPlayerRepository playerRepository) { this.teamRepository = teamRepository; this.playerRepository = playerRepository; }
// This is on PlayersController public ViewResult Index() { return View(playerRepository.GetAllPlayers(player => player.Team)); }
定义更复杂的模型类之间的关系
public class Player { public int PlayerId { get; set; } public string Name { get; set; } // This links Player to Team public int TeamId { get; set; } }
public class Team { public int TeamId { get; set; } // ... other Team properties go here // Each Team has an optional "next opponent" which is another Team public int? NextOpponentId { get; set; } [ForeignKey("NextOpponentId")] public virtual Team NextOpponent { get; set; } // Each Team also has a required Manager and Administrator, both of which are people public int ManagerId { get; set; } public int AdministratorId { get; set; } [ForeignKey("ManagerId")] public virtual Person Manager { get; set; } [ForeignKey("AdministratorId")] public virtual Person Administrator { get; set; } }