I am using Entity Framework 4.3.1 using the DbContext POCO approach against a SQL Server 2012 database.
I have just two tables in the database and they look like this:
NOTE: There are no foreign keys specified in the database at all - I am only enforcing the relationship in the model (I cannot change the database).
They each have one row of data in them that looks like this:
I performed the following query to ensure the join would work:
Now, I have the following entities:
public class Two
{
public long TwoId { get; set; }
public string OneId { get; set; }
public virtual One One { get; set; }
}
public class One
{
public string OneId { get; set; }
public DateTime DeliveryDate { get; set; }
public virtual ICollection<Two> Twos { get; private set; }
public void AddTwo(Two two)
{
if (two == null)
throw new ArgumentNullException("two");
if (Twos == null)
Twos = new List<Two>();
if (!Twos.Contains(two))
Twos.Add(two);
two.One = this;
}
}
And this is the context:
public class TestContext : DbContext
{
public TestContext(string conectionString)
: base(conectionString)
{
Configuration.LazyLoadingEnabled = true;
Ones = Set<One>();
Twos = Set<Two>();
}
public DbSet<One> Ones { get; private set; }
public DbSet<Two> Twos { get; private set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var one = modelBuilder.Entity<One>();
one.ToTable("One");
one.HasKey(d => d.OneId);
var two = modelBuilder.Entity<Two>();
two.ToTable("Two");
two.HasKey(d => new
{
d.OneId,
d.TwoId
});
two.Property(p => p.TwoId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
two.HasRequired(t => t.One)
.WithMany(o => o.Twos)
.HasForeignKey(o => o.OneId);
base.OnModelCreating(modelBuilder);
}
}
When I run this bit of code I get Why is this printed?
printed to my console - which I do not expect as you can see that the navigation property should be filled in (I even explicitly included it):
using (var ctx = new TestContext(@"......"))
{
const string oneId = "111348718";
var one = ctx.Ones.Single(o => o.OneId.Equals(oneId));
if (one != null)
{
var sdi = ctx
.Twos
.Include(s => s.One)
.Single(s => s.OneId.Equals(oneId));
if (sdi.One == null)
{
Console.WriteLine("Why is this printed?");
}
else
{
Console.WriteLine("This is what I expect");
}
}
}
Now, this is the really odd bit: If I simply comment out the DeliveryDate
property from the One
class it works fine (I get This is what I expect
printed to the console).
What's wrong here and how can I solve it?
NOTE: If I look at the DeliveryDate
property on the one
variable it has been correctly set to the expected value so the date must be OK in the database and entity framework is perfectly able to materialize it.
More Information: The fact that it is a date does not matter - if it is, say an nvarchar it still fails - seems any simple property causes the whole thing to fall over - this feels like a bug to me...