Issue while converting IFormFile to string - entity-framework

I am working a asp.netcore 3.1 project. I have 2 table with one to many relationship.
I am facing an issue in converting VideoId form IFormFile to String.
Here is my model and viewModel.
ParentModel.cs
public class Parent
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public List<child> Children { get; set; }
}
public class child
{
public int Id { get; set; }
public string VideoId { get; set; } // inside ParentModel videoId is string type
public int ParentId { get; set; }
}
ParentViewModel.cs
public class Parent
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public List<child> Children { get; set; }
}
public class child
{
public int Id { get; set; }
public IFormFile VideoId { get; set; } // inside ParentViewModel VideoId is IFormFile type
public int ParentId { get; set; }
}
ParentController.cs
public async Task<IActionResult> Create([FromForm] ParentViewModel parent)
{
var result = await _ParentService.Create(_mapper.Map<ParentModel>(parent)); // this line is ok. After this line VideoId is Microsoft.AspNetCore.Http.FormFile
if (parent.Child.Count > 0)
{
int id = 0;
foreach (var child in parent.Child){
var videoIdString = await _helper.UploadImage(child.VideoId, "path"); // In this line I convert videoId of child of ParentViewModel to string from IFormFile. Now VideoId is path.mp4
}
id++;
}
// I have to update VideoId of child of ParentModel with that coverted videoIdString
await _ParentService.Update(result);
return Created(nameof(Get), result);
}
I have to update VideoId of the child of ParentModel with converted videoIdString
How Can I do this? Anyone ideas, please...

first you don't need this DatabaseGenerated(DatabaseGeneratedOption.Identity)
because the default is on trying to understand from my code
public class MParent
{
[Key]
public int Id { get; set; }
public List<child> Children { get; set; }
}
public class Mchild
{
[Key]
public int Id { get; set; }
public string VideoId { get; set; }
public int ParentId { get; set; }
}
and view model
public class Parent
{
public int Id { get; set; }
public List<child> Children { get; set; }
}
public class child
{
public int Id { get; set; }
public IFormFile VideoId { get; set; }
public int ParentId { get; set; }
}
and my controller
[HttpPost]
public IActionResult Create(child child, IFormFile myfile)
{
Mchild mychild = new Mchild()
{
ParentId = child.ParentId,
VideoId = myfile.FileName
};
myfile.CopyToAsync(myfileLoctionTosaveVideo);
_context.add(mychild);
_context.savechanges();
return View();
}
and you can do these with file

Related

Insert in relationship table after inserting record

I have this classes and a WebApi method to POST the Item.
After inserting Item i want it to insert the inserted PK ItemId and given CategoryId into CategoryItem
public partial class Item
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public string? Type { get; set; }
}
public partial class Category
{
public int Id { get; set; }
public string? Description { get; set; }
public string? Name { get; set; }
}
public partial class Categoryitem
{
public int IdCategory { get; set; }
public int IdItem { get; set; }
public virtual Category IdCategoryNavigation { get; set; } = null!;
public virtual Item IdItemNavigation { get; set; } = null!;
}
[HttpPost]
public ActionResult<Item> PostItem(Item item)
{
_context.Item.Add(item);
_context.SaveChanges();
return Ok();
}
How do i pass the IdCategory into POST method ? Do I need a CategoryCollection in Item class and pass IdCategory through Item member ?
What about the relationship table ? How do i insert the two Ids ?
Thank you
you can create a viewmodel if you need to add several categories in the same time when you create an item, or if you only assign one category when you create an item you can just add CategoryId, but with attribute [NotMapped]
public partial class Item
{
public int Id { get; set; }
... another properties
[NotMapped]
public int? CategoryId{ get; set; }
}
or fluent api
modelBuilder.Entity<Item>().Ignore(c => c.CategoryId);
you will have to bind this CategoryId to dropdown list in the view
and action
[HttpPost]
public ActionResult<Item> PostItem(Item item)
{
var categoryitem = new Categoryitem
{
IdItemNavigation=item,
IdCategory = item.CategoryId
};
_context.Categoryitem.Add(categoryitem);
_context.SaveChanges();
return Ok(item);
}

How to create Map between two tables using where statement?

I have Doctor and Appointment tables.On my DTO I have DoctorName field and I want to bring that name from doctor table by AutoMapper.I tried to Map like below on AutoMapperProfile but it says cannot convert from 'bool' to 'System.Func<<char,bool>. Both values are string that I want to map so doesnt make sense.Here my Models,DTO and CreateMap below.
Doctor
public class Doctor
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public Department Department { get; set; }
public int DepartmentId { get; set; }
}
Appointment
public class Appointment
{
public int Id { get; set; }
public DateTime AppointmentDate { get; set; }
public int DoctorId { get; set; }
public Doctor Doctor { get; set; }
public int? PatientId { get; set; }
public Patient Patient { get; set; }
}
AutoMapperProfile
CreateMap<Appointment, AvilableAppointmentDto>()
.ForMember(dep => dep.DoctorName,
opt => opt.MapFrom(src =>
src.Doctor.Name.Where(src.DoctorId==src.Doctor.Id)));
DTO
public class AvilableAppointmentDto
{
public int Id { get; set; }
public DateTime AppointmentDate { get; set; }
public int DoctorId { get; set; }
public string DoctorName { get; set; }
}
UPDATE(Solution)
Dto should be mapped as IENumerable.Like below
var returnAppointments = _mapper.Map<IEnumerable<AvilableAppointmentDto>>(availableAppointments);
Below thing works for me
Mapping:
CreateMap<Appointment, AvilableAppointmentDto>(MemberList.Destination)
.ForMember(dep => dep.DoctorName, opt => opt.MapFrom(src => src.Doctor.Name));
Entity Classes:
public class Doctor
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public int DepartmentId { get; set; }
}
public class Appointment
{
public int Id { get; set; }
public DateTime AppointmentDate { get; set; }
public int DoctorId { get; set; }
public Doctor Doctor { get; set; }
public int? PatientId { get; set; }
}
public class AvilableAppointmentDto
{
public int Id { get; set; }
public DateTime AppointmentDate { get; set; }
public int DoctorId { get; set; }
public string DoctorName { get; set; }
}
controller:
[HttpGet]
public ActionResult Get([FromServices] IMapper mapper)
{
Appointment ap = new Appointment()
{
AppointmentDate = DateTime.Now,
DoctorId = 1,
Id = 2,
PatientId = 3,
Doctor = new Doctor()
{
Id = 1,
DepartmentId = 2,
Name = "Ajay",
Title = "Mr"
}
};
var x = mapper.Map<AvilableAppointmentDto>(ap);
return Ok(x);
}
startup.cs
public void ConfigureServices(IServiceCollection services)
{
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile<MappingProfile>();
});
var mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
}
Package ref.
<PackageReference Include="AutoMapper" Version="8.0.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="6.0.0" />

Entity Framework Include error

I have the following Model objects
public class UserEntry
{
public int UserEntryID { get; set; }
public string UserID { get; set; }
public string TeamName { get; set; }
public int Total { get; set; }
public virtual ICollection<EntryPlayer> EntryPlayers { get; set; }
}
public class EntryPlayer
{
public int EntryPlayerID { get; set; }
public bool Captain { get; set; }
public virtual int UserEntryID { get; set; }
public virtual Player Player { get; set; }
}
public class Player
{
public int PlayerID { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public int Group { get; set; }
public string Team { get; set; }
public int Score { get; set; }
}
My database schema looks like this:-
When I try and load a UserEntry using this code:-
UserEntry userEntry = this.db.UserEntries
.Where(u => u.UserID == user.Id)
.Include("EntryPlayers")
.FirstOrDefault();
I get the error:
Invalid column name 'Player_PlayerID'
If I change the Player property on my UserEntry object from:
public virtual Player Player { get; set; }
to:
public virtual int PlayerID { get; set; }
then my UserEntry object loads fine but obviously only has the PlayerID and not the whole Player object in it.
What do I need to change so that I can load the Player object within the UserEntry?
I also have this DatabaseInitializer class
namespace ACS.Models {
public class ACSDatabaseInitializer : CreateDatabaseIfNotExists<ACSContext>
{
protected override void Seed(ACSContext context)
{
base.Seed(context);
var players = new List<Player>();
players.Add(new Player
{
PlayerID = 1,
FirstName = "Dave",
MiddleInitial = "",
LastName = "Smith",
Group = 1,
Team = "Team1",
Score = 0
});
players.ForEach(p => context.Players.Add(p));
context.SaveChanges();
}
}
}
and this Context class
namespace ACS.Models
{
public class ACSContext : DbContext
{
public ACSContext()
: base("name=ACS")
{
Database.SetInitializer<ACSContext>(null);
}
public DbSet<Player> Players { get; set; }
public DbSet<UserEntry> UserEntries { get; set; }
public DbSet<EntryPlayer> EntryPlayers { get; set; }
}
}
I needed both a PlayerID property and a Player property on my UserEntry object for this to work

Entity framework insert error

I have 3 class table
and Category table have 1 record ,for example catID = 2 ...
and There is no record of the product table
now , When adding a new record to the table Images ,
When I entered CategpryID = 2 , ProductID = 0 ...
I am getting error :(
What do I need ???*
[Table("Products")]
public class Product
{
public Product()
{
Images = new List<Image>();
}
public int ProductID { get; set; }
public string Name { get; set; }
public List<Image> Images { get; set; }
}
[Table("Categorys")]
public class Category
{
public Category()
{
Images = new List<Image>();
}
public int CategpryID { get; set; }
public string Name { get; set; }
public List<Image> Images { get; set; }
}
[Table("Images")]
public class Image
{
[Key]
public int ImageID { get; set; }
public int CategpryID { get; set; }
public int ProductID { get; set; }
public string ImageURL { get; set; }
public Product Product { get; set; }
public Category Category { get; set; }
}

EF update is inserting and into a different table

I have an MVC 5 website using EF6 code first.
The website will track golf results at events.
Here are my pocos:
public class Event
{
public int EventId { get; set; }
public string VenueName { get; set; }
public string CourseName { get; set; }
public String FirstTeeOff { get; set; }
public DateTime EventDate { get; set; }
public decimal Fee { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Golfer
{
public int GolferId { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public int CurrentHandicap { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Result
{
public int ResultId { get; set; }
public Golfer Golfer { get; set; }
public Event Event { get; set; }
public bool Attendance { get; set; }
public int HandicapPlayed { get; set; }
public int ScoreCarded { get; set; }
public int LongestDriveWins { get; set; }
public int NearestPinWins { get; set; }
public Result()
{
Event = new Event();
Golfer = new Golfer();
}
}
The POST edit action for my Result is as follows:
[HttpPost]
[Authorize]
public ActionResult Edit(ResultViewModel resultVM)
{
try
{
DomainClasses.Result resultDomain = _context.Results.Find(resultVM.GolferResults[0].ResultId);
resultDomain.Attendance = resultVM.GolferResults[0].Attendance;
resultDomain.HandicapPlayed = resultVM.GolferResults[0].HandicapPlayed;
resultDomain.ScoreCarded = resultVM.GolferResults[0].ScoreCarded;
resultDomain.LongestDriveWins = resultVM.GolferResults[0].LongestDriveWins;
resultDomain.NearestPinWins = resultVM.GolferResults[0].NearestPinWins;
_context.Results.Attach(resultDomain);
_context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I'm getting an error on the SaveChanges. I've used EF Profiler and it showed that it was trying to insert into the Event table:
INSERT [dbo].[Events]
([VenueName],
[CourseName],
[FirstTeeOff],
[EventDate],
[Fee])
VALUES (NULL,
NULL,
NULL,
'0001-01-01T00:00:00' /* #0 */,
0 /* #1 */)
SELECT [EventId]
FROM [dbo].[Events]
WHERE ##ROWCOUNT > 0
AND [EventId] = scope_identity()
Any idead why?
It's most likely because you create instances of the related entities in the Result constructor:
Event = new Event();
Golfer = new Golfer();
Remove those lines from the constructor.