I’m using EntityFramework v4.3.1 and building my model via code by inheriting from DbContext and overriding OnModelCreating(). I have a table called Companies and a table called Messages. The Messages table has a nullable foreign key Messages.CompanyId. When this is set, the particular message is associated to a specific company. When this field is null, the message is associated to all companies.
My problem is that I don’t know how to express this behaviour in the OnModelCreating() method. If I do:
modelBuilder.Entity<Message>().HasRequired(o => o.Company).WithMany(o => o.Messages).Map(o => o.MapKey("CompanyId"));
I successfully get a navigation property on Company such that I can do calls like TestCompany.Messages and I get a list of messages associated to the particular company. But I also need to have all the null messages returned.
How can this be achieved?
If you want to query messages that are not associated with any company you need to model the scalar property
CompanyIdin theMessageentity class.And configure the relationship using
HasOptionalinstead ofHasRequired.Then you can query using