2013-10-03 40 views
1

我是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>(); 
    } 
} 

}

+0

如果你想为身份PK你与'DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)装饰' 您可能需要装饰用'ForeignKey的您FK字段(“​​”)属性''地方'​​是的导航性能关系。如果您不打算访问应用程序中的FK ID字段,则可以从模型中省略它们 – Moho

回答

1

您设置POCO的方式似乎没有问题。 Code First将自己完成FK技巧。 将您的List<T>设置为虚拟,以便EF可以使用Lazy Loading

如果你真的想安装,使用流利的API,在您的DAL:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    base.OnModelCreating(modelBuilder); 
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
    modelBuilder.Entity<Guitarist>().HasRequired(p => p.Guitar).WithMany(b => b.Amplifier) 
} 

伟大的想法,顺便说一下!

1

你可能想给我们e“公共虚拟ICollection”而不是“公共列表”。但是,你写的看起来不错。

public virtual ICollection<Guitar> Guitars{ get; set; } 

使用“公共虚拟ICollection”的原因是获得延期加载支持。成为一名同伴吉他手,摇滚乐!