This is probably just some simple beginner’s mistake, but I just can’t seem to figure it out.
I’m just trying to get started with entity framework (ef 5.0, .net 4.5), been rolling all my own sql statements until now. I’m trying to work with an existing database and EF code first, with two simple classes that have a one to many relationship: clips and clip_ratings (there can be zero or many ratings for each clip). the relevant parts of the classes are:
public class clip
{
public clip()
{
this.Ratings = new List<clip_ratings>();
}
public virtual ICollection<clip_ratings> Ratings { get; set; }
public int clip_id { get; set; }
public Nullable<int> clip_type { get; set; }
// ...
}
public class clip_ratings
{
public int cr_id { get; set; }
public int cr_clip_id { get; set; }
// ...
[ForeignKey("cr_clip_id")]
public clip Clip { get; set; }
}
Now I’m trying to read some data from the DB:
var query = from b in db.clips
orderby b.clip_id where b.Ratings.Count > 1
select b;
foreach (var item in query)
{
Console.WriteLine(item.Ratings.Count +" | "+item.clip_linktext);
}
The query returns the correct resultset from the DB, however it errors on the item.Ratings.Count. When I just output item.clip_linktext all is fine, but with the item.Ratings.Count I get the following error:
More than one item in the metadata collection match the identity ‘clip_ratings’.
I’ve tried following all the MS EF tutorials and reading up on some more posts, but just can’t seem to figure it out. Hope somebody here can help me along on this (and that it is easy to fix ;))
update: adding the classMap.cs sources:
public class clipMap : EntityTypeConfiguration<clip>
{
public clipMap()
{
// Primary Key
this.HasKey(t => t.clip_id);
// ...
// Table & Column Mappings
this.ToTable("clips");
this.Property(t => t.clip_id).HasColumnName("clip_id");
this.Property(t => t.clip_type).HasColumnName("clip_type");
...
}
}
public class clip_ratingsMap : EntityTypeConfiguration<clip_ratings>
{
public clip_ratingsMap()
{
// Primary Key
this.HasKey(t => t.cr_id);
// Table & Column Mappings
this.ToTable("clip_ratings");
this.Property(t => t.cr_id).HasColumnName("cr_id");
this.Property(t => t.cr_clip_id).HasColumnName("cr_clip_id");
// ...
}
}
ok, after another hour of messing with about every part of this simple example I found a solution: apparently EF didn’t like the collection being called “Ratings”, even though there’s no part in the DB or code anywhere with a property/field/attribute of that name.
Changed the name to Votes instead of Ratings to
and everything works just fine.
Guess that’s why I’ve avoided these kind of frameworks so far, you never really know what they’re doing under the hood 😉
And yes, if I get a chance to remodel the db, I will try to follow the naming conventions.
If anyone has a good explanation of why it didn’t work with Ratings, I’d still like to hear it, to be able to avoid similar situations in the future.