Почему не удается вставить в .net Web ApiC#

Место общения программистов C#
Ответить
Anonymous
 Почему не удается вставить в .net Web Api

Сообщение Anonymous »

При вставке ServiceInfo происходит сбой. Не работает внешний ключ JobResult.JobId, вот классы.
//------------------------------------------------------------------------------
//
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
//
//------------------------------------------------------------------------------

namespace PPISNetWebApi.Models
{
using System;
using System.Collections.Generic;

public partial class ServiceInfo
{
public int ServiceInfoId { get; set; }
public System.DateTime ServiceDate { get; set; }
public int LocationId { get; set; }
public int ServerId { get; set; }
public string WhoRec { get; set; }
public Nullable RelationId { get; set; }
public Nullable DOB { get; set; }
public Nullable Age { get; set; }
public Nullable RaceId { get; set; }
public string Sex { get; set; }
public string Height { get; set; }
public string Weight { get; set; }
public Nullable HairId { get; set; }
public string OtherDesc { get; set; }
public string ServiceComments { get; set; }
public Nullable Signature { get; set; }
public Nullable Hostile { get; set; }
public Nullable ServiceLocLat { get; set; }
public Nullable ServiceLocLon { get; set; }
public string PhotoFileName { get; set; }
public int DocumentJobId { get; set; }
public Nullable RateChg { get; set; }
public int JobResultId { get; set; }
public int ServiceTypeId { get; set; }
public Nullable MailDate { get; set; }
public string MailType { get; set; }
public Nullable RestDel { get; set; }
public string PropDesc { get; set; }
public Nullable DateReturned { get; set; }
public Nullable Amended { get; set; }
public string Title { get; set; }
public Nullable DateEntered { get; set; }
public Nullable TotalJobRevenue { get; set; }
public Nullable TotalCost { get; set; }
public Nullable Notary { get; set; }
public Nullable NoAtt { get; set; }
public Nullable EFilingDate { get; set; }
public string EFileNo { get; set; }

public virtual DocumentJob DocumentJob { get; set; }
public virtual Hair Hair { get; set; }
public virtual JobResult JobResult { get; set; }
public virtual Location Location { get; set; }
public virtual Race Race { get; set; }
public virtual Relation Relation { get; set; }
public virtual Server Server { get; set; }
public virtual ServiceType ServiceType { get; set; }
}
}

//------------------------------------------------------------------------------
//
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
//
//------------------------------------------------------------------------------

namespace PPISNetWebApi.Models
{
using System;
using System.Collections.Generic;

public partial class JobResult
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public JobResult()
{
this.AttReslts = new HashSet();
this.DocumentJobs = new HashSet();
this.ServiceInfoes = new HashSet();
}

public int JobResultId { get; set; }
public string JobResultName { get; set; }
public string JobResultDesc { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection AttReslts { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection DocumentJobs { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection ServiceInfoes { get; set; }
}
}

Я попробовал добавить строку вручную, отправив json в API с помощью PostMan.
{
"ServiceInfoId": 0,
"ServiceDate": "2025-09-15T00:00:00",
"LocationId": 16369,
"ServerId": 4,
"WhoRec": "Ann green ",
"RelationId": 1005,
"DOB": "1964-07-30T00:00:00",
"Age": 61,
"RaceId": 9,
"Sex": "female",
"Height": "5ft5 ",
"Weight": "111 ",
"HairId": 9,
"OtherDesc": null,
"ServiceComments": null,
"Signature": null,
"Hostile": null,
"ServiceLocLat": null,
"ServiceLocLon": null,
"PhotoFileName": null,
"DocumentJobId": 15315,
"RateChg": null,
"JobResultId": 1005,
"ServiceTypeId": 1,
"MailDate": null,
"MailType": null,
"RestDel": null,
"PropDesc": null,
"DateReturned": null,
"Amended": null,
"Title": null,
"DateEntered": null,
"TotalJobRevenue": null,
"TotalCost": null,
"Notary": null,
"NoAtt": null,
"EFilingDate": null,
"EFileNo": null
}

Я знаю, что значение JobResultId должно существовать в JobResult. JobResultId — это первичный ключ в JobResult. JobResultId 1005 существует в JobResult. Я пытаюсь сохранить данные ServiceInfo в базе данных.
Но я получаю внутреннюю ошибку сервера 500
"ExceptionMessage": "The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_ServiceInfo_JobResult\"

Я также пытался использовать приведенный ниже код для ввода строки, но получил тот же результат.
public async Task CreateServiceInfoAsync([FromBody]ServiceInfo serviceInfo, bool isNewItem)
{

Uri uri = new Uri(string.Format(Constants.RestUrl7, string.Empty));

try
{
string json = JsonSerializer.Serialize(serviceInfo, _serializerOptions);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

HttpResponseMessage response = null;
if (isNewItem)
{
response = await _client.PostAsync(uri, content);
Debug.WriteLine(content);
Debug.WriteLine(@"\tServiceInfo successfully sent.");
}
else
response = await _client.PutAsync(uri, content);

if (response.IsSuccessStatusCode)
Debug.WriteLine(@"\tServiceInfo successfully saved.");
}
catch (Exception ex)
{
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
}

Я начинающий программист-самоучка и не могу в этом разобраться. Чего мне не хватает!
USE [db_a6750e_ppisdata]
GO

/****** Object: Table [dbo].[JobResult] Script Date: 9/18/2025 4:06:34 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[JobResult](
[JobResultId] [int] IDENTITY(1,1) NOT NULL,
[JobResultName] [nchar](30) NULL,
[JobResultDesc] [nchar](60) NULL,
CONSTRAINT [PK_JobResult] PRIMARY KEY CLUSTERED
(
[JobResultId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

USE [db_a6750e_ppisdata]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_ServiceType]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_Server]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_Relation]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_Race]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_Location]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_JobResult]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_Hair]
GO
ALTER TABLE [dbo].[ServiceInfo] DROP CONSTRAINT [FK_ServiceInfo_DocumentJob]
GO
/****** Object: Table [dbo].[ServiceInfo] Script Date: 9/17/2025 8:18:46 PM ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ServiceInfo]') AND type in (N'U'))
DROP TABLE [dbo].[ServiceInfo]
GO
/****** Object: Table [dbo].[ServiceInfo] Script Date: 9/17/2025 8:18:46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ServiceInfo](
[ServiceInfoId] [int] IDENTITY(1,1) NOT NULL,
[ServiceDate] [datetime2](7) NOT NULL,
[LocationId] [int] NOT NULL,
[ServerId] [int] NOT NULL,
[WhoRec] [nchar](50) NULL,
[RelationId] [int] NULL,
[DOB] [datetime2](7) NULL,
[Age] [int] NULL,
[RaceId] [int] NULL,
[Sex] [nchar](6) NULL,
[Height] [nchar](5) NULL,
[Weight] [nchar](4) NULL,
[HairId] [int] NULL,
[OtherDesc] [nchar](50) NULL,
[ServiceComments] [nvarchar](max) NULL,
[Signature] [bit] NULL,
[Hostile] [bit] NULL,
[ServiceLocLat] [decimal](9, 6) NULL,
[ServiceLocLon] [decimal](9, 6) NULL,
[PhotoFileName] [nchar](150) NULL,
[DocumentJobId] [int] NOT NULL,
[RateChg] [decimal](6, 2) NULL,
[JobResultId] [int] NOT NULL,
[ServiceTypeId] [int] NOT NULL,
[MailDate] [datetime2](7) NULL,
[MailType] [nchar](25) NULL,
[RestDel] [bit] NULL,
[PropDesc] [nvarchar](max) NULL,
[DateReturned] [datetime2](7) NULL,
[Amended] [bit] NULL,
[Title] [nchar](40) NULL,
[DateEntered] [datetime2](7) NULL,
[TotalJobRevenue] [decimal](7, 2) NULL,
[TotalCost] [decimal](7, 2) NULL,
[Notary] [bit] NULL,
[NoAtt] [int] NULL,
[EFilingDate] [datetime2](7) NULL,
[EFileNo] [nchar](15) NULL,
CONSTRAINT [PK_ServiceInfo] PRIMARY KEY CLUSTERED
(
[ServiceInfoId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_DocumentJob] FOREIGN KEY([DocumentJobId])
REFERENCES [dbo].[DocumentJob] ([DocumentJobId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_DocumentJob]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_Hair] FOREIGN KEY([HairId])
REFERENCES [dbo].[Hair] ([HairId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_Hair]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_JobResult] FOREIGN KEY([JobResultId])
REFERENCES [dbo].[JobResult] ([JobResultId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_JobResult]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_Location] FOREIGN KEY([LocationId])
REFERENCES [dbo].[Location] ([LocationId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_Location]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_Race] FOREIGN KEY([RaceId])
REFERENCES [dbo].[Race] ([RaceId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_Race]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_Relation] FOREIGN KEY([RelationId])
REFERENCES [dbo].[Relation] ([RelationId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_Relation]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_Server] FOREIGN KEY([ServerId])
REFERENCES [dbo].[Server] ([ServerId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_Server]
GO
ALTER TABLE [dbo].[ServiceInfo] WITH CHECK ADD CONSTRAINT [FK_ServiceInfo_ServiceType] FOREIGN KEY([ServiceTypeId])
REFERENCES [dbo].[ServiceType] ([ServiceTypeId])
GO
ALTER TABLE [dbo].[ServiceInfo] CHECK CONSTRAINT [FK_ServiceInfo_ServiceType]
GO



Подробнее здесь: https://stackoverflow.com/questions/797 ... et-web-api
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»