Reputation: 1071
I have a Model with a class like this
public class Feature
{
public int ID { get; set; }
public string Desc { get; set; }
}
and one like this:
public class Camera
{
public int ID { get; set; }
public string ModelName { get; set; }
public List<Feature> Features { get; set; }
}
in the Seed() method I do something like this:
context.Features.AddOrUpdate
(
f => f.Desc,
new Feature { Desc = "PTZ" },
new Feature { Desc = "AutoFocus" },
new Feature { Desc = "AutoIris" },
new Feature { Desc = "PoE" }
);
context.Cameras.AddOrUpdate
(
c => c.Name,
new Camera
{
ModelName = "P3301",
Features = new System.Collections.Generic.List<Feature>()
{
context.Features.Where(f => f.Desc.Contains("PTZ")).First()
}
}
);
context.Cameras.AddOrUpdate
(
c => c.Name,
new Camera
{
ModelName = "P3301p",
Features = new System.Collections.Generic.List<Feature>()
{
context.Features.Where(f => f.Desc.Contains("PoE")).First(),
context.Features.Where(f => f.Desc.Contains("PTZ")).First()
}
}
);
After running update-database I see the records in the Features and Cameras tables, but the Features table has a new Camera_ID field that contains a single Camera ID. I was expecting a Feature_Camera table or something so that a feature could be crossed up with many different cams.
What am I missing here? How do I say that a camera can have a a collection of non-unique features?
Upvotes: 1
Views: 145
Reputation: 177153
If you want a many-to-many relationship between Camera
and Feature
either add a collection to Feature
...
public List<Camera> Cameras { get; set; }
...or define the relationship with Fluent API:
modelBuilder.Entity<Camera>()
.HasMany(c => c.Features)
.WithMany()
.Map(m =>
{
m.ToTable("CameraFeatures"); // name of the link table
m.MapLeftKey("CameraID");
m.MapRightKey("FeatureID");
});
If you don't do one of these changes EF will assume that the relationship is one-to-many resulting in a foreign key to Camera
in the Feature
s table.
Upvotes: 1