【问题标题】:SQLite Error 19: 'UNIQUE constraint failed: PosterDto.Id'SQLite 错误 19:“唯一约束失败:PosterDto.Id”
【发布时间】:2021-10-06 03:59:02
【问题描述】:

当我尝试发布新项目时,会发生以下事情。 在这个应用程序中使用了 API 的 Mediator。

  1. 查找实际登录的用户,
  2. 创建 Poster 的新对象(以减少发送到 DB 的数据并获得有关谁创建了新 Item 的一些信息),
  3. 创建 Item 的新对象
  4. 更新数据库

在 Postman 中,出现错误:

"errors": "An error occurred while updating the entries. See the inner exception for details."

当我检查终端时,有更具体的错误:

SQLite Error 19: 'UNIQUE constraint failed: PosterDto.Id'.

海报DTO:

public class PosterDto
{
        public string Id { get; set; }
        public string DisplayName { get; set; }
        public string Username { get; set; }
        public string Photo { get; set; }
}

项目:

public class Item
{
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime Date { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
        public string Image { get; set; }
        public PosterDto Poster { get; set; }
        public ICollection<Message> Messages { get; set; } = new List<Message>();
}

创建项目类:

public class Create
    {
        public class Command : IRequest 
        {
            public Guid Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public DateTime Date { get; set; }
            public double Latitude { get; set; }
            public double Longitude { get; set; }
            public string Image { get; set; }
        }

        public class Validator : AbstractValidator<Command>
        {
            public Validator()
            {
                RuleFor(x => x.Id).NotEmpty();
                RuleFor(x => x.Title).NotEmpty().WithMessage("Please specify a title");
                RuleFor(x => x.Description).NotEmpty().WithMessage("Please specify a description");
                RuleFor(x => x.Latitude).NotEmpty();
                RuleFor(x => x.Longitude).NotEmpty();
            }
        }

        public class Handler : IRequestHandler<Command>
        {
            private readonly DataContext _context;
            private readonly UserManager<AppUser> _userManager;
            private readonly IUserAccessor _userAccessor;

            public Handler(DataContext context, UserManager<AppUser> userManager, IUserAccessor userAccessor)
            {
                _context = context;
                _userManager = userManager;
                _userAccessor = userAccessor;
            }

            public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var user = await _userManager.FindByNameAsync(_userAccessor.GetCurrentUsername());

                if (user == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { user = "Not found" });
                }

                var poster = new PosterDto
                {
                    Id = user.Id,
                    DisplayName = user.DisplayName,
                    Username = user.UserName,
                    Photo = user.Photo
                };

                var item = new Item
                {
                    Id = request.Id,
                    Title = request.Title,
                    Description = request.Description,
                    Date = DateTime.Now,
                    Latitude = request.Latitude,
                    Longitude = request.Longitude,
                    Image = request.Image,
                    Poster = poster
                };

                _context.Items.Add(item);

                var success = await _context.SaveChangesAsync() > 0;

                if (success)
                {
                    return Unit.Value;
                }

                throw new NotImplementedException("Error");
            }
        }
    }

ItemsController:

[HttpPost]
public async Task<ActionResult<Unit>> Create(Create.Command command)
{
    return await _mediatR.Send(command);
}

【问题讨论】:

  • Id = request.Id,我看不到请求的声明位置。请发布整个代码
  • 将您的“海报”添加到上下文中
  • @Romka 到底是什么意思?
  • @Serge 代码已更新
  • 尝试在上下文海报表中添加新的“海报”对象

标签: c# entity-framework asp.net-core


【解决方案1】:

您遇到的问题与实体框架有关。我猜你是先使用代码。

public class Item
{       
   // Entity Framework will create a relationship between PosterDto and Item 
    public PosterDto Poster { get; set; }
}

Entity Framework 将在 PosterDto 和 Item 之间创建关系。 要防止 EntityFramework 这样做,请将属性 [NotMapped] 添加到 PosterDto 属性。

public class Item
{       
   // Add NotMapped Attribute
    [NotMapped]
    public PosterDto Poster { get; set; }
}

看看这篇文章https://www.learnentityframeworkcore.com/configuration/data-annotation-attributes/notmapped-attribute

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多