我有一个包含3个表的数据库。旅游,优惠和TourOffers。旅游包含旅游的地点和价格。优惠是旅游和TourOffers商店的特别优惠,提供什么旅游。
以下示例:
当我首先从现有数据库生成代码时,两个类是从Tours和Offers表中创建的。
如何使用ToursOffers表来保持表之间的关系?例如,游览进入组合框,如何在文本框中显示所选的游览项目。
我的功能代码:
private void onload(object sender, EventArgs e)//Populate Product Name drop down.
{
Tours tour = new tours();
dataSource = tour.GetAll();
comboBox1.DisplayMember = "Tour"; // set display member
comboBox1.ValueMember = "PID"; // value member as Id to use at selectedIndex changed
comboBox1.DataSource = dataSource;
offerSource = tour.GetAllOffers();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.DataSource = dataSource;
decimal price = dataSource.Where(x => x.PID == (int)comboBox1.SelectedValue)
.FirstOrDefault().Price.Value;
textBox1.Text = price.ToString("0.00"); // set result to two decimal places
textBox2.Text = //RELATED OFFER
}
我给出了一个想法:
string offers = offerSource
.Where(x => x.Equals(comboBox1.SelectedValue))
.FirstOrDefault().OfferDescription;
发生System.NullReferenceException HResult = 0x80004003
Message =对象引用未设置为对象的实例。
编辑1
Tours生成了类:
public partial class Tour
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Tour()
{
Offers = new HashSet<Offer>();
}
public int PID { get; set; }
[Required]
[StringLength(40)]
public string Tour { get; set; }
[Column(TypeName = "money")]
public decimal? Price { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Offer> Offers { get; set; }
}
提供生成的课程:
public partial class Offer
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Offer()
{
Products = new HashSet<Product>();
}
public int OfferID { get; set; }
[Required]
[StringLength(60)]
public string Desc { get; set; }
[StringLength(10)]
public string Code { get; set; }
}
模特:
public Model1()
: base("name=Model1")
{
}
public virtual DbSet<Offer> Offers { get; set; }
public virtual DbSet<Tour> Tours { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Offer>()
.Property(e => e.Code)
.IsFixedLength();
modelBuilder.Entity<Offer>()
.HasMany(e => e.Tours)
.WithMany(e => e.Offers)
.Map(m => m.ToTable("TourOffers").MapLeftKey("OfferID").MapRightKey("PID"));
modelBuilder.Entity<Tour>()
.Property(e => e.Price)
.HasPrecision(19, 4);
}