We used following workaround:
delete the foreign key directly after creating the model. Not beautiful but effective.
Pergunta
I have following legacy code fragment that I can't change:
public class EntityA
{
int SeqId { get; set; } //Not part of the key
[Association("EntityB", "Seq_ID", "Seq_ID")]
public EntityB EntityB { get; set; }
}
public class EntityB
{
[Key]
int SeqId { get; set; }
}
Database was created via SQL and not with Entity Framework. There are no foreign keys and the relation is handled as one to one/zero.
Now, we must use the model for code first and Entity Framework adds a foreign key relation. Since I can't change the model, but I can override the OnModelCreating event, I want to rewrite the relationship from required to optional. I was trying to add
modelBuilder.Entity<EntityA>().Property(i => i.EntityB).IsOptional();
and
modelBuilder.Entity<EntityA>().HasOptional(i => i.EntityB).WithOptionalDependent()
but in both cases Entity Framework complains.
Solução
We used following workaround:
delete the foreign key directly after creating the model. Not beautiful but effective.