我是EF Code First方法的新手,我遇到了一些麻烦。我真的需要你的帮助..
我有3个类,如下面
[Table("Customers")]
public class Customer
{
public long Id { get; set; }
public string Name { get; set; }
public string MiddleName { get; set; }
public string Surname { get; set; }
public string FirmName { get; set; }
public string ShortName { get; set; }
public virtual ICollection<CustomerEmail> CustomerEmails { get; set; }
public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; }
}
[Table("CustomerEmail")]
public class CustomerEmail
{
public long Id { get; set; }
public string Email { get; set; }
public DateTime RecordTime { get; set; }
public virtual Customer Customer { get; set; }
}
[Table("CustomerAddress")]
public class CustomerAddress
{
public long Id { get; set; }
public Int16 CountryCode { get; set; }
public Int16 CityCode { get; set; }
public string City { get; set; }
public string Town { get; set; }
public string District { get; set; }
public string Street { get; set; }
public string PostalCode { get; set; }
public virtual Customer Customer { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<CustomerEmail> CustomerEmails { get; set; }
public DbSet<CustomerAddress> CustomerAddresses { get; set; }
}
我的问题
1) 当我运行应用程序时,它无法找到客户的相关表,即CustomerAddress和CustomerEmail。它给出了一个错误,说“Customer_Id不会退出CustomerEmail和CustomerAddress表”。我认为这些模型之间的关系有问题。我需要你的帮助改善这些关系。
2)获取客户数据没有问题。但它带来了所有数据。例如我在客户表中有10.0000行,它在我的上下文类中带来了10.000行。这不好。我不希望它带来首先是所有数据。我想在查询时带来相关的数据。
伙计们,我很快就会需要你的帮助。谢谢......
答案 0 :(得分:2)
由于您没有遵循EF外键约定,因此您需要通过Fluent映射将这些关系设置为DbContext类。寻找关于流利映射的博客,以了解如何建立一对一的关系
也许您在没有where子句的情况下执行linq查询。请输入与此项目相关的一些代码。
答案 1 :(得分:1)
[Table("CustomerAddress")]
public class CustomerAddress
{
public long Id { get; set; }
public long CustomerId { get; set; }
public Int16 CountryCode { get; set; }
public Int16 CityCode { get; set; }
public string City { get; set; }
public string Town { get; set; }
public string District { get; set; }
public string Street { get; set; }
public string PostalCode { get; set; }
public virtual Customer Customer { get; set;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerAddresses>()
.HasKey(a => a.CustomerId)
.HasRequired(a => a.Customer)
.WithMany(b => b.CustomerAddresses)
.HasForeignKey(a => a.Id);
}
当我查询context.Customers.Find(3);
Customer的CustomerAddresses属性中应该有2行,但只有一行是第一行。为什么它只带一行?我试图建立1-n关系