0
I have a problem that I cannot solve in any way with Entity Framework.
In this scenario I am receiving information from the front, and then I need to save it in the database, however, when I have 2 information where the Fileid is the same and the Usecaseid and the Order field are different. Only 1 line is saved.
Usecaseid and Fileid Foreign keys from other tables, the relationship is just below:
modelBuilder.Entity<Content>()
.HasIndex(ct => ct.FileId)
.IsUnique(false);
modelBuilder.Entity<Content>()
.HasIndex(ct => ct.UseCaseId)
.IsUnique(false);
modelBuilder.Entity<Content>()
.HasKey(cn => cn.ContentId);
modelBuilder.Entity<Content>()
.HasOne(cn => cn.File)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Content>()
.HasOne(cn => cn.UseCase)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
In this example below is a case where two exactly equal contents need to be saved, varying only the Usecase, but only the last of the list is saved in the Database.
Parameter received in the way.
This is the code where the problem occurs:
[HttpPost]
public JsonResult Create([FromBody] ContentJson data)
{
List<Content> contents = new List<Content>();
var contentName = string.Empty;
var array = data.content;
int order;
for (int i = 0; i < array.Count; i++)
{
var files = JsonConvert.DeserializeObject<string[]>(array[i][1].ToString());
if (files == null || files.Length == 0)
continue;
contentName = array[i][0].ToString();
order = 1;
foreach(var fileName in files)
{
Content content = new Content();
content.Order = order;
content.UseCaseId = long.Parse(contentName);
content.FileId = unitOfWork.FileRepository.Get(f => f.FileName.Equals(fileName)).First().FileId;
contents.Add(content);
order++;
}
}
unitOfWork.ContentRepository.AddRange(contents);
unitOfWork.Save();
return Json(Ok());
}
The Contentid is automatically generated by the updated Database, Entityframework and dotnet. I have tried to add and save to each iteration, but the same problem happens. I tried to use Equals and Hashcode, but it didn’t work. I’m trying in many ways but it doesn’t work. Can someone please help me ?
Can someone please help me ?
Can add the
data
exactly as it is received by the controller?– tvdias
I added, basically it is receiving a string and a "Dictionary" in the form of an "Array Array".
– Jose Aguiar