对于一对多关系,HasMany和OwnsMany 有什么区别?我什么时候应该使用一个?
例如:
public class xxx
{
public virtual IReadOnlyCollection<xxxHistoryEntity> Histories => _histories;
private readonly List<xxxHistoryEntity> _histories = new List<xxxHistoryEntity>();
}
public class xxxHistoryEntity : Entity<string>
{
public string State { get; set; }
public string NodeId { get; set; }
public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
实体配置:
class xxxConfiguration
: IEntityTypeConfiguration<xxx>
{
public void Configure(EntityTypeBuilder<xxx> builder)
{
builder.OwnsMany(itm => itm.Histories, collbuilder =>
{
collbuilder.HasForeignKey("xxxid");
});
}
}
class xxxHistoryConfiguration …
Run Code Online (Sandbox Code Playgroud) 我正在使用EF Core连接到已部署到Azure App Services的Azure SQL数据库。我正在使用访问令牌(通过托管身份获取)连接到Azure SQL数据库。
这是我的做法:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
//code ignored for simplicity
services.AddDbContext<MyCustomDBContext>();
services.AddTransient<IDBAuthTokenService, AzureSqlAuthTokenService>();
}
Run Code Online (Sandbox Code Playgroud)
MyCustomDBContext.cs
public partial class MyCustomDBContext : DbContext
{
public IConfiguration Configuration { get; }
public IDBAuthTokenService authTokenService { get; set; }
public CortexContext(IConfiguration configuration, IDBAuthTokenService tokenService, DbContextOptions<MyCustomDBContext> options)
: base(options)
{
Configuration = configuration;
authTokenService = tokenService;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = Configuration.GetConnectionString("defaultConnection");
connection.AccessToken = authTokenService.GetToken().Result;
optionsBuilder.UseSqlServer(connection);
}
}
Run Code Online (Sandbox Code Playgroud)
AzureSqlAuthTokenService.cs …
azure-active-directory entity-framework-core azure-sql-database ef-core-2.2
我正在使用 Entity Framework Core 2.2.6 对 Sql Server 数据库运行一个简单的查询,但是 GroupBy 没有在服务器上执行,而是在本地执行。
有什么我遗漏的东西会迫使该组进入服务器吗?
我尝试过的 EF 查询的 2 个变体:
public class Holiday
{
public int Id {get;set;}
public DateTime Date {get;set;}
public string Username {get;set;}
public string Approver {get;set;}
}
//version 1
await _dbContext.Holidays
.GroupBy(h => new { h.Date})
.ToDictionaryAsync(x => x.Key.Date, x => x.Select(x1 => x1.Username).ToList());
//version 2
await _dbContext.Holidays
.GroupBy(h => h.Date)
.ToDictionaryAsync(x => x.Key, x => x.Select(x1 => x1.Username).ToList());
Run Code Online (Sandbox Code Playgroud)
两种变体都会产生以下 SQL:
SELECT [h].[Id], [h].[Approver], [h].[Date], [h].[HolidayTypeId], [h].[OwningRequestId], [h].[HolidayStatusId], [h].[Username] …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 EF 核心 2.2 构建带有空间对象的数据库,但在尝试创建数据库迁移时遇到问题。使用https://docs.microsoft.com/en-us/ef/core/modeling/spatial,特别是:
class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
// Database includes both Polygon and MultiPolygon values
public IGeometry Border { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用此创建迁移,则会出现以下错误:
属性“Country.Border”属于接口类型(“IGeometry”)。如果它是导航属性,则通过将其转换为映射实体类型来手动配置此属性的关系,否则使用 NotMappedAttribute 或“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略该属性。
同样,如果我将其更改为 Geometry 类型,则会得到:
无法映射属性“Geometry.UserData”,因为它属于“object”类型,它不是受支持的基本类型或有效的实体类型。显式映射此属性,或使用 '[NotMapped]' 属性或使用 'OnModelCreating' 中的 'EntityTypeBuilder.Ignore' 忽略它。
我不知道我的对象是点、线还是多边形,所以它必须是通用的。我如何在我的结构中表示它?另外我看到有些地方说我需要添加以下代码:
public class MyDBContextFactory : IDesignTimeDbContextFactory<MyDBContext>
{
public MyDBContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<MyDBContext>();
builder.UseSqlServer(cnnString, x => x.UseNetTopologySuite());
return new MyDBContext(builder.Options);
}
} …
Run Code Online (Sandbox Code Playgroud) 我正在使用EF Core Power Tools
版本2.4.0
与Miccrosoft.EntifyFrameworkCore.SqlServer
版本2.2.6
IsActive
当[IsActive] [bit] NOT NULL
我使用 EF Core Power Tool 的逆向工程来生成实体和数据库上下文时,我定义了 SQL 表列。
问题
该工具生成可为空的布尔属性,而不仅仅是布尔值
public bool? IsActive { get; set; }
对应DBContext的OnModelCreating方法
modelBuilder.Entity<Scenario>(entity =>
{
entity.Property(e => e.ScenarioID).HasColumnName("ScenarioID");
entity.Property(e => e.IsActive)
.IsRequired()
.HasDefaultValueSql("((1))");
}
Run Code Online (Sandbox Code Playgroud) 我知道时态表旨在为您提供数据的时间点视图。我正在使用时态表进行审计。我有以下临时表。
让我们假设这是临时表的当前状态:
ID RoleID UserID ModifiedBy
------------------------------------------
1 11 1001 foo@example.com
2 22 1001 foo@example.com
3 33 1002 bar@example.com
4 11 1003 foo@example.com
Run Code Online (Sandbox Code Playgroud)
我有一个使用 EF Core 的 Web 应用程序。我的 EF 代码总是将 设置ModifiedBy
为当前登录的用户。我以身份登录应用程序bar@example.com
并删除了 ID 为 2 的记录。SQL Server 将按预期自动将删除的记录插入历史记录表中,并保持 ModifiedBy 为,foo@example.com
因为这是 ModifiedBy 列的时间点值。
但是现在系统不知道是谁删除了该行。在这种情况下,bar@example.com
是实际删除该行的人。如何捕获删除记录的用户?我在这里有哪些选择?
我正在尝试在 EF Core 中构建一个理智的查询,该查询返回一组事物,而这些事物又是从事物集合中派生出来的。基本上在原始 SQL 中,会执行 JOIN。
它在 ASP.NET Core 中,因此初始集合是SecurityPrincipal
对象上的角色列表:
var roles = User.FindAll(ClaimTypes.Role).Select(r=>r.Value);
Run Code Online (Sandbox Code Playgroud)
这些角色然后映射到我们数据库中的组,所以我可以查找这些:
var groupsQuery = dbContext.Groups.Where(g=>roles.Any(r=>r==g.GroupName));
var groups = await groupsQuery.ToListAsync();
Run Code Online (Sandbox Code Playgroud)
这个查询很愉快,并按预期返回了一组组。然而,这些组可以访问另一个资源,这正是我真正想要的,因为它是多对多的关系,所以有一个桥接表。
这是我尝试查询 AssetGroup 连接表,以便我可以获取映射到SecurityPrincipal
.
var assetGroupsQuery = dbContext.AssetsGroups.Where(ag => groupsQuery.Any(ag => ag.Id == a.GroupId));
var assetGroups = await assetGroupsQuery.ToListAsync();
Run Code Online (Sandbox Code Playgroud)
当我执行第二个查询时,我在输出窗口中收到很多垃圾邮件:
The LINQ expression 'where ([ag].Id == [ag].GroupId)' could not be translated and will be evaluated locally.
The LINQ expression 'Any()' could not be translated and will be evaluated locally.
The LINQ …
Run Code Online (Sandbox Code Playgroud) c# entity-framework linq-to-sql entity-framework-core ef-core-2.2
我正在尝试在已创建数据库的现有系统上构建一个 aspnetcore 应用程序,我将在其上添加一些表。
我对数据库进行了逆向工程,将现有表作为实体添加到我的应用程序中,并且我编写了自己的实体,稍后将添加这些实体。最后,所有实体都添加到单个 DbContext 中。
我的要求如下:
注意:我不想接触生成的迁移代码。
有没有合适的方法来处理这种情况?
entity-framework ef-database-first entity-framework-migrations ef-core-2.2
我有一个 ASP .Net Core 2.2 Web API。在我的一个控制器操作中,我向 MySQL 数据库表中添加了一堆行(我使用的是 Pomelo)。
例如:
_dbContext.AddRange(entities);
_dbContext.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
我添加的实体有两个主键(复合主键),当我将它们添加到 DbContext 时,这些键已经填充在实体集合中(即我自己设置键 - 没有“自动增量”或类似的东西数据库生成密钥的地方)
如果我添加的任何实体已经存在于数据库中,就重复的主键而言,那么显然 SaveChanges() 会抛出异常,并且整个事务将回滚。
有没有办法告诉 EF Core 忽略失败的实体?即忽略数据库中已经存在的实体,并提交成功的实体(即数据库中不存在的实体)?而不是抛出异常并回滚整个事务的当前行为?
谢谢
mysql dbcontext asp.net-core ef-core-2.2 entity-framework-core-2.2
我正在尝试建立这样的查询
var d = dbContext.Picks
.Where( /* some conditions */ )
.GroupBy(x => new { gameDiff = x.Schedule.GameTotal.Value - x.TieBreakerScore.Value })
.Select(g => new { name = g.Key.firstname, count = g.Count(),
gameDiff = Math.Abs(g.Key.gameDiff) })
.OrderByDescending(x => x.count)
.ThenBy(x => x.gameDiff)
.Take(top)
.ToList();
Run Code Online (Sandbox Code Playgroud)
但是当我运行这个我得到
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'AS'.'
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Incorrect syntax near the keyword 'AS'.
Source=Core .Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at …
Run Code Online (Sandbox Code Playgroud) ef-core-2.2 ×10
c# ×4
asp.net-core ×2
dbcontext ×1
ef-core-2.1 ×1
entity-framework-migrations ×1
linq-to-sql ×1
mysql ×1
spatial ×1
sql-server ×1
t-sql ×1