Reputation: 280
None of the Q&A I've found so far seem to resolve this problem.
I'm in the process of migrating from a custom DAL to EF6, so entity classes and DB already exist. I'm trying to keep DataAnnotations out of the entity classes.
A LiveCourseOpportunity can have a Campaign. And a Campaign can have a LiveCourseOpportunity (at least in the sense that the Campaign class has to have a Navigation Property pointing to its LiveCourseOpportunity). In the database, this is implemented as the LiveCourseOpportunities table having CampaignId as an FK.
Here is the (relevant) code I have so far:
LiveCourseOpportunity entity
public int DatabaseId { get; set; } // PK
public int? CampaignId { get; set; }
public virtual Campaign Campaign { get; set; }
Campaign entity
public int DatabaseId { get; set; } // PK
public virtual ICollection<LiveCourseOpportunity> LiveCourseOpportunities { get; set; }
Model
modelBuilder.Entity<Campaign>()
.HasKey(T => T.DatabaseId)
.Property(T => T.DatabaseId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<LiveCourseOpportunity>()
.HasKey(T => T.DatabaseId)
.Property(T => T.DatabaseId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Campaign>()
.HasMany(c => c.LiveCourseOpportunities)
.WithOptional(o => o.Campaign)
.HasForeignKey(o => o.CampaignId);
The relationship directly above comes from an EF reverse-engineering of the database... one-to-many for some reason.
Can anyone advise proper mapping to get this done?
Upvotes: 1
Views: 133
Reputation: 109080
For a database, a foreign key is always one to many unless the key field has a unique index.
However, in EF you can map it as an optional one to one association (0..1 - 0..1):
modelBuilder.Entity<Campaign>()
.HasOptional(e => e.LiveCourseOpportunity)
.WithOptionalPrincipal(e => e.Campaign)
.Map(m => m.MapKey("CampaignId"));
The database still doesn't know better than that it's 0..1-n (i.e. there is a nullable foreign key CampaignId
), but EF will execute validations to enforce a one-to-one association.
Upvotes: 1