EF核心:实体需要一个钥匙 - 但它确实有一个钥匙
我正在使用EF Core,并且具有以下项目结构
AppName.Entity
- 警报
- 其他类
AppName.Repository
- alertrepository
- 其他存储库类的
警报实体如下:
using System;
using System.ComponentModel.DataAnnotations;
namespace AppName.Entity
{
public class Alert
{
[Key]
public int AlertId { get; set; }
public string RuleId { get; set; }
public string DeviceId { get; set; }
public string VehicleVin { get; set; }
public string AlertText { get; set; }
public DateTime DateTimeUtc { get; set; }
public AlertCategory AlertCategory { get; set; }
}
public enum AlertCategory
{
VehicleHealth = 1,
FleetHealth = 2,
EmissionsHealth = 3,
Fuel = 4,
AssetUtilization = 5,
Safety = 6,
DutyCycle = 7
}
}
alertrepository .cs
如下:
using AppName.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppName.Repository
{
public class AlertRepository// : GenericRepository<Alert>, IAlertRepository
{
public async Task<int> Save(Alert alert)
{
using (AFIdbContext context = new AFIdbContext())
{
context.Alerts.Add(alert);
await context.SaveChangesAsync();
return alert.AlertId;
}
}
public async Task<bool> Save(IEnumerable<Alert> alerts)
{
using (AFIdbContext context = new AFIdbContext())
{
foreach (Alert alert in alerts)
{
context.Alerts.Add(alert);
}
await context.SaveChangesAsync();
return true;
}
}
public IQueryable<Alert> GetList(DateTime fromDate, DateTime toDate, int pageSize, int pageNum)
{
using (AFIdbContext context = new AFIdbContext())
return context.Alerts.Where(x => x.DateTimeUtc >= fromDate && x.DateTimeUtc <= toDate).Skip(pageSize * pageNum).Take(pageSize);
}
}
}
fidbcontext.cs
using AppName.Entity;
using Microsoft.EntityFrameworkCore;
using System.Configuration;
namespace AppName.Repository
{
public class AFIdbContext : DbContext
{
private string _afiConnstring;
public string AFIConnstring
{
get
{
if (_afiConnstring != null)
return _afiConnstring;
else
return "";
}
}
public AFIdbContext() : base()
{
}
public AFIdbContext(DbContextOptions<AFIdbContext> options) : base(options)
{
}
public DbSet<Alert> Alerts { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserAlertPreference> UserAlertPreferences { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AlertRepository>().ToTable("Alert");
modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<UserAlertPreference>().ToTable("UserAlertPreference");
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(AppExtensions.ConnString);
}
}
}
当我尝试保存警报集合时,我会得到以下例外:
system.invalidoperationException:'实体类型“ alertrepository”需要定义一个主键。如果您打算使用无钥匙实体类型呼叫“ hasnokey()”。
警报
实体确实具有DB中的主键,并且确实具有[key]
属性。为什么告诉我alertrepository
对象是我要保存的alert
实体时没有密钥集?我可以在一个单独的项目中没有实体吗?我正在尝试遵循DDD模式,
即使试图保存记录之前,就已经引发了例外
(我在等待上下文上有一个断点
。 ://i.sstatic.net/mpqve.png“ rel =” nofollow noreferrer“>
I'm using EF Core and have the following project structure
AppName.Entity
- Alert
- Other classes
AppName.Repository
- AlertRepository
- Other Repository classes
The alert entity is as follows:
using System;
using System.ComponentModel.DataAnnotations;
namespace AppName.Entity
{
public class Alert
{
[Key]
public int AlertId { get; set; }
public string RuleId { get; set; }
public string DeviceId { get; set; }
public string VehicleVin { get; set; }
public string AlertText { get; set; }
public DateTime DateTimeUtc { get; set; }
public AlertCategory AlertCategory { get; set; }
}
public enum AlertCategory
{
VehicleHealth = 1,
FleetHealth = 2,
EmissionsHealth = 3,
Fuel = 4,
AssetUtilization = 5,
Safety = 6,
DutyCycle = 7
}
}
AlertRepository.cs
is as follows:
using AppName.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppName.Repository
{
public class AlertRepository// : GenericRepository<Alert>, IAlertRepository
{
public async Task<int> Save(Alert alert)
{
using (AFIdbContext context = new AFIdbContext())
{
context.Alerts.Add(alert);
await context.SaveChangesAsync();
return alert.AlertId;
}
}
public async Task<bool> Save(IEnumerable<Alert> alerts)
{
using (AFIdbContext context = new AFIdbContext())
{
foreach (Alert alert in alerts)
{
context.Alerts.Add(alert);
}
await context.SaveChangesAsync();
return true;
}
}
public IQueryable<Alert> GetList(DateTime fromDate, DateTime toDate, int pageSize, int pageNum)
{
using (AFIdbContext context = new AFIdbContext())
return context.Alerts.Where(x => x.DateTimeUtc >= fromDate && x.DateTimeUtc <= toDate).Skip(pageSize * pageNum).Take(pageSize);
}
}
}
AFIdbContext.cs
using AppName.Entity;
using Microsoft.EntityFrameworkCore;
using System.Configuration;
namespace AppName.Repository
{
public class AFIdbContext : DbContext
{
private string _afiConnstring;
public string AFIConnstring
{
get
{
if (_afiConnstring != null)
return _afiConnstring;
else
return "";
}
}
public AFIdbContext() : base()
{
}
public AFIdbContext(DbContextOptions<AFIdbContext> options) : base(options)
{
}
public DbSet<Alert> Alerts { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserAlertPreference> UserAlertPreferences { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AlertRepository>().ToTable("Alert");
modelBuilder.Entity<User>().ToTable("User");
modelBuilder.Entity<UserAlertPreference>().ToTable("UserAlertPreference");
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(AppExtensions.ConnString);
}
}
}
When I attempt to save a collection of Alerts, I get the following exception:
System.InvalidOperationException: 'The entity type 'AlertRepository' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.'
The Alert
entity does have a primary key in the DB and does have the [Key]
attribute. Why is it telling me that the AlertRepository
object doesn't have the key set when it's an Alert
Entity I am trying to save? Can I not have the Entity in a separate project? I'm trying to follow a DDD pattern
The exception is being thrown before it even tries to save the records
(I have a breakpoint on await context.SaveChangesAsync();
in AlertRepository
The solution here doesn't help because I already have those set
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Alertrepository是一个实体不是正确的类,您只需要在 onModeLcreating 中映射警报实体
替换,
或者
您只能删除此行,因为实体框架将为您创建一个与您的名称相同的表格实体。
AlertRepository is not right class to be an entity, you just have to map the Alert entity in OnModelCreating
Replace
with
or you can just remove this line because entity framework will create a table for you with same name as your entity.
您已经在
onModeLcreating
中绘制了错误的实体 table警报。尝试
You have mapped the wrong entity in your
OnModelCreating
for table Alert.Try with