简体   繁体   中英

Some many to one objects missing in DataGridView

HI I have two Tables( Movie as Movy Entity and Producers as Producer ). Movie has one producer and producer has many movies.here is the er diag Picture: ER Diagram

When i set the data soure of my DataGridView to ctx.Movies.ToList() some movie in the list doesnt have any producer. even though its not null in database. Picture:Program with missing producer

 //Movie Entity Class public partial class Movy { public short VideoCode { get; set; } public string MovieTitle { get; set; } public string MovieType { get; set; } public string Rating { get; set; } public Nullable<float> RentalPrice { get; set; } public string ProducerID { get; set; } public string Director { get; set; } public string Media { get; set; } public Nullable<short> TotalStock { get; set; } public Nullable<short> NumberRented { get; set; } public virtual Producer Producer { get; set; } } } //Producer Entity Class public partial class Producer { public Producer() { this.Movies = new HashSet<Movy>(); } public string ProducerID { get; set; } public string ProducerName { get; set; } public string CountryCode { get; set; } public virtual ICollection<Movy> Movies { get; set; } } // MyDBEntities ctx public partial class MYDBEntities : DbContext { public MYDBEntities() : base("name=MYDBEntities") { } public virtual DbSet<Movy> Movies { get; set; } public virtual DbSet<Producer> Producers { get; set; } } //this is my function in windows form which is having some producer missing in movie datalist. i have added the picture of output private void Form1_Load(object sender, EventArgs e) { MYDBEntities ct = new MYDBEntities(); dataGridView1.DataSource = ct.Movies.ToList(); } 

PS: [Picture:Database data]

 /* i checked each product and its producer. some producer is null there. even though its not null in database(I have uploaded db pic) [3]*/ List<Movy> ls = ct.Movies.ToList(); foreach(Movy mov in ls) { //some mov.Producer is null here. } 

You can try with Include method.

MYDBEntities ct = new MYDBEntities();
dataGridView1.DataSource = ct.Movies.Include("Producer").ToList();

Alright I found the problem. it is Entity Framework wasn't able to automap some string foreign key. for me those movie was having producerID = 'Universal' foreign key, that movies Producer Object was null(Couldn't map). so once I update my database like using following query follwoing: it working now: update Movies set Producer='Warner' where Producer='Universal';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM