1

我是 ASP.NET 和 EF 的新手,但有 Ruby MVC 经验。我正在开发一个具有一对多关系的复杂应用程序,因此我创建了一个较小的项目,我可以使用它来测试 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>();
    }
}

}

4

2 回答 2

1

您可能想要使用“public virtual ICollection”而不是“public List”。不过,你写的看起来不错。

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

使用“public virtual ICollection”的原因是为了获得延迟加载支持。与吉他手同行,摇滚吧!

于 2013-10-03T20:58:19.537 回答
1

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

如果您真的想设置,请在 DAL 中使用 Fluent API:

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

好主意,顺便说一句!

于 2013-10-03T21:00:59.860 回答