Hi,
looks like there's a behavior I don't understand. Here's the code and I'll reference the [X] in comment marked lines.
Can somebody explain it to me?
Tested in EF 6.1.1.
looks like there's a behavior I don't understand. Here's the code and I'll reference the [X] in comment marked lines.
class Program
{
static void Main(string[] args)
{
using (var ctx = new TestContext())
{
Console.WriteLine((ctx as IObjectContextAdapter).ObjectContext.CreateDatabaseScript());
}
}
}
[DbConfigurationType(typeof(TestContextConfiguration))]
class TestContext : DbContext
{
public DbSet<TestClass> TestClasses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// [A] lightweight on Properties
modelBuilder.Properties()
.Where(x => x.Name.Equals("Key", StringComparison.InvariantCulture))
.Configure(x => x.IsKey());
// [B] lightweight on Types
modelBuilder.Types()
.Having(x => x.GetProperties().Select(y => y.Name).Where(y => y.Equals("Key", StringComparison.InvariantCulture)))
.Configure((x, k) => x.HasKey(k));
var testConf = modelBuilder.Entity<TestClass>();
// [C] calling Property
testConf.Property(x => x.Key).HasMaxLength(10);
}
}
class TestContextConfiguration : DbConfiguration
{
public TestContextConfiguration()
{
SetDatabaseInitializer<TestContext>(null);
}
}
class TestClass
{
public string Key { get; set; }
public string FooBar { get; set; }
}
The [A] defines a convention where every property named "Key" is considered entity key. That works fine as long as you don't call Property on some class. The [C] line. That completely "resets" the entity key and you'll get exception that the entity set has no key. Surprisingly defining the convention based on "Types" call (the [B]) works fine. What's more confusing is the [C] line can be just "Property" method call and not any "IsXxx" or "HasXxx" further and it's still "reset".Can somebody explain it to me?
Tested in EF 6.1.1.