我是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