我有以下实体:
然后我有另一个名为Notes的实体。每个实体都可以有很多Notes,如何使用代码第一个流畅的API实现这一点?目标是在Notes表上有一个对象Id,这个实体id将指向正确的实体。
答案 0 :(得分:1)
您可以使用映射Notes属性的新基类扩展每个实体(例如WithComment) 而且你可以编写一个类来映射新属性:
public class WithComment
{
public virtual IList<Note> Notes { get; set; }
}
public class Customer : WithComment
{
}
public class CustomerMapping : EntityTypeConfiguration<Customer>
{
public CustomerMapping ()
{
ToTable( "Customers" );
..........................
HasMany<Notes>( o => o.Notes); // relation to note class
}
}
然后添加配置
public class MyContext : DbContext
{
public MyContext() { }
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
modelBuilder.Configurations.Add( new CustomerMapping() );
base.OnModelCreating( modelBuilder );
}
}
答案 1 :(得分:0)
实体框架不支持开箱即用的异构关联(其他框架,如NHibernate,确实如此)
我的解决方法是使用NoteService
来存储和检索持久实体的注释。
这是一个简化的摘录:
public ICollection<Note> GetNotes(IEntity entity)
{
var entityType = ObjectContext.GetObjectType(entity.GetType()).Name;
return context.Query<Note>()
.Where(x => x.EntityId == entity.Id &&
x.EntityType == entityType)
.ToList();
}
public void AddNote(IEntity entity, Note note)
{
note.EntityType = ObjectContext.GetObjectType(entity.GetType()).Name;
note.EntityId = entity.Id;
context.Add(note);
}