C# 如何为继承数据结构使用代码优先的Fluent API?
我有一个代码优先的应用程序,其定义如下:C# 如何为继承数据结构使用代码优先的Fluent API?,c#,entity-framework,ef-code-first,datamapper,C#,Entity Framework,Ef Code First,Datamapper,我有一个代码优先的应用程序,其定义如下: public abstract class Entity { [Key] public int Id { get; set; } public DateTime CreatedOn { get; set; } } public class Post : Entity { public string Text { get; set; } public virtual ICollection<UserObje
public abstract class Entity
{
[Key]
public int Id { get; set; }
public DateTime CreatedOn { get; set; }
}
public class Post : Entity
{
public string Text { get; set; }
public virtual ICollection<UserObject> Likes { get; set; }
}
public class Blog : Post
{
public string Title { get; set; }
public string Content { get; set; }
}
public class Comment : Post
{
public string Content { get; set; }
public virtual Post Parent { get; set; }
}
public class UserObject : Entity
{
public string Username { get; set; }
public string Login { get; set; }
}
public class Profile : UserObject
{
public DateTime DoB { get; set; }
public string Avatar { get; set; }
public ICollection<Blog> Blogs { get; set; }
}
表配置文件
Id
...
表PostLikes
Id
PostId
UserId
表ProfileBlogs
Id
UserId
BlogId
我尝试过,但无法使用Fluent API生成这些方案。我尝试使用多对多关系,但因为我的数据结构具有继承性,所以它不起作用
如何在Fluent API中实现这一点?以下是一个对我有用的模式: fluent映射:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Profile>()
.Map(m => m.ToTable("Profiles"));
modelBuilder.Entity<Post>()
.HasMany(p => p.Likes)
.WithMany()
.Map(m =>
{
m.ToTable("PostLikes");
m.MapLeftKey("PostId");
m.MapRightKey("UserId");
});
modelBuilder.Entity<Profile>()
.HasMany(p => p.Blogs)
.WithMany()
.Map(m =>
{
m.ToTable("ProfileBlogs");
m.MapLeftKey("UserId");
m.MapRightKey("BlogId");
});
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.Map(m=>m.ToTable(“Profiles”);
modelBuilder.Entity()
.HasMany(p=>p.Likes)
.有很多
.Map(m=>
{
m、 ToTable(“PostLikes”);
m、 MapLeftKey(“posted”);
m、 MapRightKey(“用户ID”);
});
modelBuilder.Entity()
.HasMany(p=>p.Blogs)
.有很多
.Map(m=>
{
m、 ToTable(“ProfileBlogs”);
m、 MapLeftKey(“用户ID”);
m、 MapRightKey(“博客ID”);
});
}
已创建此数据库:
你好,谢谢你。但是我创建UserObject的原因是加载“完整”配置文件有时有些过分,特别是UserObjects被广泛使用。我已经更新了答案,以拥有一个用户对象表,因此您可以创建任意一个实体
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Profile>()
.Map(m => m.ToTable("Profiles"));
modelBuilder.Entity<Post>()
.HasMany(p => p.Likes)
.WithMany()
.Map(m =>
{
m.ToTable("PostLikes");
m.MapLeftKey("PostId");
m.MapRightKey("UserId");
});
modelBuilder.Entity<Profile>()
.HasMany(p => p.Blogs)
.WithMany()
.Map(m =>
{
m.ToTable("ProfileBlogs");
m.MapLeftKey("UserId");
m.MapRightKey("BlogId");
});
}