I have a lot of one association between "Project" and "Template".
The project has a property of type "Template".
The association is not bidirectional (the "Template" does not know the "Project").
My entity mapping for the association in the "Project":
this.HasOptional(p => p.Template);
If I create a "Project" without specifying a template, then zero is correctly inserted in the "TemplateId" column of the "Projects" table.
If I specify a template, the template identifier will be inserted correctly. Generated SQL:
update [Projects]
set [Description] = '' ,
[UpdatedOn] = '2011-01-16T14:30:58.00' ,
[ProjectTemplateId] = '5d2df249-7ac7-46f4-8e11-ad085c127e10'
where (([Id] = '8c1b2d30-b83e-4229-b0c3-fed2e36bf396' )
and [ProjectTemplateId] is null)
However, if I try to change the template or even set it to null, templateId is not updated. Generated SQL:
update [Projects]
set [UpdatedOn] = '2011-01-16T14:32:14.00'
where ([Id] = '8c1b2d30-b83e-4229-b0c3-fed2e36bf396' )
As you can see, TemplateId is not updated.
. "Template" "Project" null , , , , !
,
[]
, , IDbSet DbContext. , , . :
public class PortfolioContext : DbContext, IDbContext
{
public PortfolioContext(string connectionStringName) : base(connectionStringName) { }
public IDbSet<Foo> Foos { get; set; }
public IDbSet<Bar> Bars { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
modelBuilder.Configurations.Add(new FooMap());
modelBuilder.Configurations.Add(new BarMap());
base.OnModelCreating(modelBuilder);
}
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class {
return base.Set<TEntity>();
}
}
public class Foo {
public Guid Id { get; set; }
public string Name { get; set; }
public virtual Bar Bar { get; set; }
public Foo()
{
this.Id = Guid.NewGuid();
}
}
public class Bar
{
public Guid Id { get; set; }
public string Name { get; set; }
public Bar()
{
this.Id = Guid.NewGuid();
}
}
public class FooMap : EntityTypeConfiguration<Foo>
{
public FooMap()
{
this.ToTable("Foos");
this.HasKey(f => f.Id);
this.HasOptional(f => f.Bar);
}
}
public class BarMap : EntityTypeConfiguration<Bar>
{
public BarMap()
{
this.ToTable("Bars");
this.HasKey(b => b.Id);
}
}
:
[Test]
public void Template_Test()
{
var ctx = new PortfolioContext("Portfolio");
var foo = new Foo { Name = "Foo" };
var bar = new Bar { Name = "Bar" };
foo.Bar = bar;
ctx.Set<Foo>().Add(foo);
ctx.SaveChanges();
object fooId = foo.Id;
object barId = bar.Id;
ctx.Dispose();
var ctx2 = new PortfolioContext("Portfolio");
var dbFoo = ctx2.Set<Foo>().Find(fooId);
dbFoo.Bar = null;
ctx2.SaveChanges();
}
, SQL CE 4.