我一直在使用EF Code First,但这是我第一次使用EF7。
我有以下模型类,其中Venue与Show有一对多的关系:
public class Show
{
public int Id { get; set; }
public Venue Venue { get; set; }
//...
}
public class Venue
{
public int Id { get; set; }
public string Name {get; set; }
//...
public List<Show> Shows { get; set; }
}
我像这样设置了DBContext:
public class NettlesContext : DbContext
{
public DbSet<Show> Shows { get; set; }
public DbSet<Venue> Venues { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
new ShowConfiguration(builder.Entity<Show>());
new ImageConfiguration(builder.Entity<Image>());
}
}
public class ShowConfiguration
{
public ShowConfiguration(EntityTypeBuilder<Show> builder)
{
builder.Property(p => p.Id).IsRequired();
builder.Property(p => p.Title).IsRequired();
}
}
public class VenueConfiguration
{
public VenueConfiguration(EntityTypeBuilder<Venue> builder)
{
builder.Property(p => p.Id).IsRequired();
builder.Property(p => p.Name).IsRequired();
}
}
然后在一些启动代码中我像这样初始化数据库:
private static void AddShows(NettlesContext db)
{
var shows = new List<Show>()
{
new Show()
{
Title = "Portland Country Dance Community Contra Dance",
Venue = new Venue()
{
Name = "Fulton Community Center",
},
},
new Show()
{
Title = "Portland Roadhouse Contra Dance",
Venue = new Venue()
{
Name = "Milwaukie Community Club",
},
},
};
db.Shows.AddRange(shows);
db.SaveChanges();
}
显示表已正确初始化,但VenueId为空。场地表完全是空的。
发生了什么事?
答案 0 :(得分:2)
DbSet.Add
有第二个参数。
Add(TEntity entity, GraphBehavior behavior = GraphBehavior.IncludeDependents)
虽然默认为IncludeDependents
(也称为儿童实体),但EF7的Add()
行为并未将Venue
标识为Show
的孩子。在OnModelCreating
中,您需要指定Venue
和Show
之间的关系。请参阅EF7文档中的Relationships。
示例:
modelBuilder.Entity<Venue>(entityBuilder =>
{
entityBuilder
.HasMany(v => v.Shows)
.WithOne(s => s.Venue)
.HasForeignKey(s => s.VenueId);
});
即使这样,你仍然需要在Venue的新实例上调用.Add,因为Show不是Venue的依赖(孩子)。
private static void AddShows(NettlesContext db)
{
var fulton = new Venue()
{
Name = "Fulton Community Center",
};
var club = new Venue()
{
Name = "Milwaukie Community Club",
};
db.Venues.Add(fulton);
db.Venues.Add(club);
var shows = new List<Show>()
{
new Show()
{
Title = "Portland Country Dance Community Contra Dance",
Venue = fulton,
},
new Show()
{
Title = "Portland Roadhouse Contra Dance",
Venue = club
},
};
context.Shows.AddRange(shows);
}
值得注意的是:.Add()的这种行为一直是EF7 RC1的混乱源,其行为可能在EF7 RC2中发生变化。请参阅https://github.com/aspnet/EntityFramework/pull/4132
答案 1 :(得分:0)
您需要更新您的模型
public class Venue
{
public int Id { get; set; }
public string Name {get; set; }
//...
public List<Show> Shows { get; set; }
}
public class Show
{
public int Id { get; set; }
public int VenueId { get; set; }
[ForeignKey("VenueId")]
public Venue Venue { get; set; }
//...
}
ForegnKey属性用于定义两个表之间关系的foriegn键