我目前在EF Core遇到了一些问题.我有一些我需要删除的数据,我很想知道流畅的API如何工作,完全与.OnDelete()
函数有关.
考虑到微软自己的网站的经典博客/帖子情景,我想知道什么实体,正是OnDelete()
"目标"(缺乏一个更好的词)在某些情况下,它似乎是博客,在其他情况下,帖子.是否可以从双方定义Cascade删除(当父博客是删除帖子时),如果是这样,我想代码应该如下所示:
model.Entity<Post>().HasOne(p => p.Blog).WithMany(b => b.Posts).HasForeignKey(p => p.BlogId).OnDelete(DeleteBehavior.Cascade)
据我所知,这是说"当博客被删除时,首先删除引用此博客的所有帖子"意味着OnDelete(DeleteBehavior.Cascade)
适用于博客,而不是发布.
但这是一样的吗?
model.Entity<Blog>().HasMany(b => b.Posts).WithOne(p => p.Blog).OnDelete(DeleteBehavior.Cascade)
或者是否OnDelete(DeleteBehavior.Cascade)
适用于Post而不是博客?
c# entity-framework-core .net-core asp.net-core-2.0 ef-core-2.0
我有一个新的.NET Core Web API项目,它具有以下项目结构:
API - >业务/域 - >基础架构
只有API方法,API非常薄.业务/域层具有我的所有业务逻辑.最后,我的Infrastructure层使用EF Core 2.0创建了我的DB类.
我知道使用.NET Core内置依赖注入我可以将API项目的引用添加到Infrastructure项目,然后在StartUp.cs文件中添加以下代码:
services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString));
Run Code Online (Sandbox Code Playgroud)
但是,我想保持更传统的关注点分离.到目前为止,我在我的Infrastructure层添加了一个模块,试图进行如下注册:
builder.Register(c =>
{
var config = c.Resolve<IConfiguration>();
var opt = new DbContextOptionsBuilder<MyContext>();
opt.UseSqlServer(config.GetSection("ConnectionStrings:MyConnection:ConnectionString").Value);
return new MyContext(opt.Options);
}).AsImplementedInterfaces().InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)
但是,DBContext没有注册.尝试访问注入的DBContext的任何类都无法解析该参数.
有没有办法在.NET Core Web API项目中使用AuftoFac在单独的项目中注册DBContext?
对于可选关系(当外键可以接受时Null
),ClientSetNull
自 EF Core 2.0 以来引入了一个新行为作为删除行为的默认选项DeleteBehavior.ClientSetNull
。这具有SetNull
跟踪实体的语义和Restrict
未加载到内存中的数据库记录的(无操作)行为。
微软文档说:
如果您希望数据库即使在未加载子实体时也尝试将空值传播到子外键,请使用
SetNull
. 但是,请注意,数据库必须支持这一点,并且像这样配置数据库可能会导致其他限制,这在实践中通常会使此选项不切实际。这就是 SetNull 不是默认设置的原因。
但我认为,当关联的父实体被删除(db 中的每个地方)时,将依赖实体的 FK 设置为 Null 通常是正常的。而且,如上所述的那些“其他限制,这在实践中经常使这个选项不切实际......”是什么?
我正在运行efcore 2.0.1.
我有一个模特:
public class BigAwesomeDinosaurWithTeeth
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public ICollection<YummyPunyPrey> YummyPunyPrey { get; set; }
}
public class YummyPunyPrey
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid? BigAwesomeDinosaurWithTeethId { get; set; }
[ForeignKey("BigAwesomeDinosaurWithTeethId")]
public BigAwesomeDinosaurWithTeeth BigAwesomeDinosaurWithTeeth { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我对这两个课程没有流利的api.但是当我生成迁移时
constraints: table =>
{
table.PrimaryKey("PK_YummyPunyPrey", x => x.Id);
table.ForeignKey(
name: "FK_YummyPunyPrey_BigAwesomeDinosaurWithTeeth_BigAwesomeDinosaurWithTeethId",
column: x => x.BigAwesomeDinosaurWithTeethId,
principalTable: "BigAwesomeDinosaurWithTeeth",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
Run Code Online (Sandbox Code Playgroud)
为什么它生成onDelete:ReferentialAction.Restrict当文档说它应该作为ClientSetNull …
entity-framework ef-code-first entity-framework-core ef-core-2.0
我有一个名为 DTO 的项目PersonDetail
和一个名为Person
. 当我打电话
db.People.Where(p => p.FirstName == "Joe").Union(db.People.Where(p => Age > 30)).ProjectTo<PersonDetail>(mapperConfig).ToList();
Run Code Online (Sandbox Code Playgroud)
我没有得到PersonDetail
DTO 和实体框架(核心)抛出异常的消息:
ArgumentException:输入序列必须具有“Test.Module.Entities.Person”类型的项目,但它具有“Test.Module.Dtos.PersonDetail”类型的项目。
当我运行代码时:
db.People.Where(p => p.FirstName == "Joe").Union(db.People.Where(p => Age > 30)).ToList();
Run Code Online (Sandbox Code Playgroud)
我Person
毫无例外地得到了实体。
这是一个工作计划(有工会):
{value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities.Person]).Where(entity => ((entity != null) And ((63ed0ebd-2c02-4496-ac8d-b836cbf13259 = = entity.CreatedBy) 或 (393a6bb0-b437-4664-beb0-6800f509451b == entity.CreatedBy)))).Union(value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities.Person] ))}
现在这是相同的计划,但也有自动映射器投影:
{value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities.Person]).Where(entity => ((entity != null) And ((63ed0ebd-2c02-4496-ac8d-b836cbf13259 = = entity.CreatedBy) 或 (393a6bb0-b437-4664-beb0-6800f509451b == entity.CreatedBy)))).Union(value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities.Person] )).Select(dto => new …
EF Core 中 .WillCascadeOnDelete(false) 的等价物是什么?
modelBuilder.Entity<ProductTransactionHistoryClassImport>()
.HasMany(e => e.ProductTransactionHistoryClassDetailImports)
.WithOne(e => e.ProductTransactionHistoryClassImport)
.WillCascadeOnDelete(false);
Run Code Online (Sandbox Code Playgroud) 我刚刚开始将我的MVC5项目与EF6x一起移植到MVC Core和EF Core,但我的实体配置存在很大问题.如何将EF6 Fluent配置迁移到EF核心?
如果可能的话,我需要带样本的指南.
这是我的一个映射类和我的尝试
EntityMappingConfiguratuin
public interface IEntityMappingConfiguration
{
void Map(ModelBuilder b);
}
public interface IEntityMappingConfiguration<T> : EntityMappingConfiguration where T : class
{
void Map(EntityTypeBuilder<T> builder);
}
public abstract class EntityMappingConfiguration<T> : EntityMappingConfiguration<T> where T : class
{
public abstract void Map(EntityTypeBuilder<T> b);
public void Map(ModelBuilder b)
{
Map(b.Entity<T>());
}
}
public static class ModelBuilderExtenions
{
private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface)
{
return assembly.GetTypes().Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
} …
Run Code Online (Sandbox Code Playgroud) 我能够将枚举作为字符串存储在数据库中.
builder.Entity<Company>(eb =>
{
eb.Property(b => b.Stage).HasColumnType("varchar(20)");
});
Run Code Online (Sandbox Code Playgroud)
但是,当需要查询时,EF不知道将字符串解析为枚举.我该如何查询:
context
.Company
.Where(x => x.Stage == stage)
Run Code Online (Sandbox Code Playgroud)
这是一个例外:将varchar值'Opportunity'转换为数据类型int时转换失败
我有这个型号:
public class Subject
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public int LevelId { get; set; }
[ForeignKey("LevelId")]
public Level Level { get; set; }
[Column(TypeName = "datetime2")]
public DateTime? DeletedAt { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并通过Fluent API配置索引:
entityBuilder.HasIndex(e => new { e.LevelId, e.Name, e.DeletedAt })
.IsUnique();
Run Code Online (Sandbox Code Playgroud)
它正在创建一个具有唯一过滤索引的表.如何防止EF添加过滤器?我只想要索引,不要过滤它.
在EF Core 2.0中,我们能够从IEntityTypeConfiguration
更清晰的Fluent API映射(源代码)派生.
如何扩展此模式以使用基础实体?在下面的示例中,我如何才能BaseEntityConfiguration
减少重复,LanguageConfiguration
并MaintainerConfiguration
修改BaseEntity
仅在BaseEntityConfiguration
?中的属性?这样的BaseEntityConfiguration
样子会是什么样的; 如果有的话,如何使用OnModelCreating()
?请参阅示例末尾附近的TODO代码.
例:
public abstract class BaseEntity
{
public long Id { get; set; }
public DateTime CreatedDateUtc { get; set; }
public DateTime? ModifiedDateUtc { get; set; }
}
public class Language : BaseEntity
{
public string Iso6392 { get; set; }
public string LocalName { get; set; }
public string Name { get; set; }
} …
Run Code Online (Sandbox Code Playgroud) c# entity-framework-core ef-fluent-api asp.net-core ef-core-2.0
ef-core-2.0 ×10
c# ×5
.net-core ×3
asp.net-core ×1
autofac ×1
automapper ×1
cascade ×1
projection ×1
union ×1