EF核心:实体需要一个钥匙 - 但它确实有一个钥匙

发布于 2025-02-10 05:19:35 字数 4383 浏览 3 评论 0原文

我正在使用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“>

在这里< /a>无济于事,因为我已经设置了

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

enter image description here

The solution here doesn't help because I already have those set

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

[旋木] 2025-02-17 05:19:35

Alertrepository是一个实体不是正确的类,您只需要在 onModeLcreating 中映射警报实体

替换,

modelBuilder.Entity<AlertRepository>().ToTable("Alert");

或者

modelBuilder.Entity<Alert>().ToTable("Alert")

您只能删除此行,因为实体框架将为您创建一个与您的名称相同的表格实体。

AlertRepository is not right class to be an entity, you just have to map the Alert entity in OnModelCreating

Replace

modelBuilder.Entity<AlertRepository>().ToTable("Alert");

with

modelBuilder.Entity<Alert>().ToTable("Alert")

or you can just remove this line because entity framework will create a table for you with same name as your entity.

つ低調成傷 2025-02-17 05:19:35

您已经在onModeLcreating中绘制了错误的实体 table警报。

尝试

modelBuilder.Entity<Alert>().ToTable("Alert")

You have mapped the wrong entity in your OnModelCreating for table Alert.

Try with

modelBuilder.Entity<Alert>().ToTable("Alert")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文