我是ASP.NET和EF的新手,但拥有Ruby MVC的经验。我正在研究一个具有一对多关系的复杂应用程序,因此我创建了一个可以与CodeFirst一代玩并测试的小型项目,以及比使用吉他项目进行测试更有趣的项目!你们所有的音乐家都知道一对多的关系,因为一个吉他手拥有几把吉他和放大器。这段代码的工作原理是,当我种下它时,它创建了数据库和表格 - 只是想就如何更好地实现它以及任何可能的陷阱提供一些建议?用外键创建CodeFirst模型
感谢
namespace GuitarCollector.Models
{
public class Guitarist
{
public Guitarist()
{
Guitars = new List<Guitar>();
Amplifiers = new List<Amplifier>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Guitar> Guitars { get; set; }
public List<Amplifier> Amplifiers { get; set; }
}
public class Guitar
{
//Primary Key
public int Id { get; set; }
//Foreign Key
public int GuitaristId { get; set; }
public int YearOfManufacture { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Finish { get; set; }
public string SerialNumber { get; set; }
public double AppraisedValue { get; set; }
Guitarist Guitarist { get; set; }
}
public class Amplifier
{
//Primary Key
public int Id { get; set; }
//Foriegn Key
public int GuitaristId { get; set; }
public int YearOfManufacture { get; set; }
public int Wattage { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public double AppraisedValue { get; set; }
public Guitarist Guitarist { get; set; }
}
}
命名空间GuitarCollector.DAL { 公共类GuitaristContext:的DbContext {
public DbSet<Guitarist> Guitarists { get; set; }
public DbSet<Guitar> Guitars { get; set; }
public DbSet<Amplifier> Amplifiers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
如果你想为身份PK你与'DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)装饰' 您可能需要装饰用'ForeignKey的您FK字段(“”)属性''地方'是的导航性能关系。如果您不打算访问应用程序中的FK ID字段,则可以从模型中省略它们 – Moho