I have a OrderDetails table. I'm trying to get all its contents but its not working. If someone can point out why it's not getting any data that would be very helpful. And yes I have data in OrderDetails table and connection is alright.
OrderDetail.cs
public class OrderDetail
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int odid { get; set; }
public int oid { get; set; }
public virtual Order order { get; set; }
public int pid { get; set; }
public int qty { get; set; }
public int total { get; set; }
public virtual Product Aproduct { get; set; }
}
OrderDetailsController.cs
private static readonly IOrderDetailRepository _orders = new OrderDetailRepository();
// GET api/<controller>
public IEnumerable<OrderDetail> Get()
{
return _orders.GetAll();
}
OrderDetailRepository.cs
private readonly MediaSoftContext _db;
public OrderDetailRepository()
{
_db = new MediaSoftContext();
}
public IEnumerable<OrderDetail> GetAll()
{
return _db.OrderDetails;
}
Related
I'm Learning Webapi so I'm trying to build a simple Api connected to SQL server and I got this error when I add new Movie data
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Movies_SuperHeroes_HeroId". The conflict occurred in database "SupersDb", table "dbo.SuperHeroes", column 'HeroId'.
I have two models :
Superhero Model:
namespace SuperHeroesApi.Models
{
public class SuperHero
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HeroId { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(100)]
public string FirstName { get; set; }
[MaxLength(100)]
public string LastName { get; set; }
[MaxLength(100)]
public string City { get; set; }
}
}
Movie Model :
namespace SuperHeroesApi.Models
{
public class Movie
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId { get; set; }
[Required]
[MaxLength(100)]
public string Title { get; set; }
public int Year { get; set; }
public double Rate { get; set; }
public byte [] Poster { get; set; }
[ForeignKey("SuperHero")]
public int HeroId { get; set; }
//public string SuuperHeroName { get; set; }
public virtual SuperHero SuperHero { get; set; }
}
}
dto :
namespace SuperHeroesApi.Otds
{
public class MoviesDtos
{
public string Title { get; set; }
public int Year { get; set; }
public double Rate { get; set; }
public IFormFile Poster { get; set; }
[ForeignKey("SuperHero")]
public int HeroId { get; set; }
}
}
MoviesController:
using SuperHeroesApi.Otds;
namespace SuperHeroesApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MoviesController : ControllerBase
{
private readonly AppDbContext _dbContext;
private new List<string> _allowedExtention = new List<string> { "jbg", "png" };
private long _maxAllowedPosterSize = 5242880;
public MoviesController(AppDbContext dbContext)
{
_dbContext = dbContext;
}
[HttpGet]
public async Task<IActionResult>GetAllAsync()
{
var movie = await _dbContext.Movies.ToListAsync();
return Ok(movie);
}
[HttpPost]
public async Task <IActionResult> CreateAsync([FromForm] MoviesDtos dto)
{
if (_allowedExtention.Contains(Path.GetExtension(dto.Poster.FileName).ToLower()))
return BadRequest();
using var dataStream = new MemoryStream();
await dto.Poster.CopyToAsync(dataStream);
var movie = new Movie
{
Title = dto.Title,
Year = dto.Year,
Rate = dto.Rate,
Poster = dataStream.ToArray(),
};
await _dbContext.AddAsync(movie);
_dbContext.SaveChanges();
return Ok(movie);
}
}
}
You probably already have existing rows before you made changes to your schema. Now that you're creating a new foreignkey HeroId in movie which cannot be null and an integer for that matter which means it will be a zero by default. It becomes a problem for the existing rows because they will try to reference a Hero entity with Id of 0 which doesn't exist. So, the obvious solution is to make the foreign key nullable and redo the migrations
[ForeignKey("SuperHero")]
public int? HeroId { get; set; }
Currently I'm creating a new feature. It looks simple, but I am stuck at a problem with automapping dto to another one.
I have to create a wishlist [adding /deleting items of wishlist].
All works fine, except one thing: while adding an item to the wishlist, I'm get a message like this:
"type": "AutoMapperMappingException",
"message": "Error mapping types..."
However, I can see it got inserted into the database. Also, can delete it too. I understand the problem is linked to Automapper, but I could not figure out how to map correctly.
[HttpPost]
public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
{
var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);
var itemCreated = await _wishListItemService.AddAsync(itemAdd);
return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
}
//service
public async Task<WishlistItemDto> AddAsync(WishlistItemDto item)
{
var entity = _mapper.Map<WishlistItem>(item);
var entityDetails = await _productDetailsRepository.GetById(item.ProductDetailId);
entity.ProductDetails = entityDetails;
await _wishListItemRepository.AddAsync(entity);
return _mapper.Map<WishlistItemDto>(entity);
}
DTOs:
public class WishListItemCreationDto
{
[Required]
public string CustomerId { get; set; }
[Required]
public int ProductDetailId { get; set; }
[Min(1)]
[Required]
public int Quantity { get; set; }
}
public class WishlistItemDto
{
public int Id { get; set; }
public string CustomerId { get; set; }
public int ProductDetailId { get; set; }
public ProductDetailsDtoWithPrimaryImage ProductDetails { get; set; }
public int Quantity { get; set; }
}
public class WishlistItem
{
public int Id { get; set; }
public string CustomerId { get; set; }
public Customer Customer { get; set; }
public int ProductDetailsId { get; set; }
public ProductDetails ProductDetails { get; set; }
public int Quantity { get; set; }
}
ProductDetails DTO:
public class ProductDetails
{
public int Id { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
public IList<ProductAttributeValue> ProductAttributes { get; set; } = new List<ProductAttributeValue>();
public int Quantity { get; set; }
public string Sku => $"BRD{Id}";
public byte[] RowVersion { get; set; } = new byte[0];
}
public class ProductDetailsDtoWithPrimaryImage
{
public int Id { get; set; }
public int Quantity { get; set; }
public int ProductId { get; set; }
public ProductDisplayEntity Product { get; set; }
public IEnumerable<ProductAttributeWithValueDto> ProductAttributes { get; set; }
public byte[] RowVersion { get; set; }
public string Sku => $"BRD{Id}";
public int? PrimaryImageId { get; set; }
}
AutoMapper:
public WishlistItemProfile()
{
CreateMap<WishlistItem, WishListItemCreationDto>().ReverseMap();
CreateMap<WishlistItemDto, WishListItemCreationDto>().ReverseMap();
CreateMap<WishlistItem, WishlistItemDto>()
.ForMember(wi => wi.ProductDetailId, opt => opt.MapFrom(f => f.ProductDetailsId))
.ForMember(wi => wi.ProductDetails, opt => opt.MapFrom(f => f.ProductDetails))
.ReverseMap();
}
everything is okay, but you missed inner mapping of your classes.
What the error says:
Mapping types:
ProductDetailsDtoWithPrimaryImage -> ProductDetails
SimpleWebApi.Controllers.ProductDetailsDtoWithPrimaryImage -> SimpleWebApi.Controllers.ProductDetails
Add additional mapping in your constructor WishlistItemProfile
CreateMap<ProductDetails, ProductDetailsDtoWithPrimaryImage>().ReverseMap();
And it starts works perfect
I am trying to find a simple way using AutoMapper to return all companies that are linked to a specific User Id in a many-to-many relationship scenario. I followed the SO Automapper many to many mapping but I get the error message "Expression of type 'System.Collections.Generic.List`1[API.Entities.CompanySetting]' cannot be used for parameter of type 'System.Linq.IQueryable" when trying to follow the logic.
My AppUser entity:
public class AppUser
{
public int Id { get; set; }
public string UserName { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
My CompanySetting entity:
public class CompanySetting
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
public virtual ICollection<AppUserCompanySetting> AppUserCompanySettings { get; set; } = new List<AppUserCompanySetting>();
}
And I have the Join table
public class AppUserCompanySetting
{
public int AppUserId { get; set; }
public virtual AppUser AppUser { get; set; }
public int CompanySettingsId { get; set; }
public virtual CompanySetting CompanySettings { get; set; }
}
I then created a CompanySettingDto
public class CompanySettingDto
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyRegistrationNumber { get; set; }
public bool isActive { get; set; }
public bool isArchived { get; set; }
}
And a MemberDto:
public class MemberDto
{
public int Id { get; set; }
public string Username { get; set; }
public string PhotoUrl { get; set; }
public string KnownAs { get; set; }
public int TimeActive { get; set; }
public DateTime LastActive {get; set;}
public ICollection<PhotoDto> Photos { get; set; }
public ICollection<CompanySettingDto> CompanyInformation { get; set; }
}
I then tried Automapper to bring the relationships between the User and the Company Information I require:
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<AppUser, MemberDto>()
.ForMember(dest => dest.CompanyInformation, opt => opt.MapFrom(x => x.AppUserCompanySettings.Select(y => y.CompanySettings).ToList()))
CreateMap<CompanySetting, CompanySettingDto>();
}
}
I am writing an API call to get all companies that are linked to a specific UserId.
public async Task<IEnumerable<MemberDto>> GetCompaniesByUserIdAsync(int userId)
{
return await _context.Users
.Where(x => x.Id == userId)
.ProjectTo<MemberDto>(_mapper.ConfigurationProvider)
.ToListAsync();
}
I am creating a view file in SQL Server as shown in the image below.
and I created a model to get results from this view:
public class FactALLCousumption : BaseEntity, IAggregateRoot
{
public double sumActiveImportTotal { get; set; }
public DateTime hour { get; set; }
public int fullDateAlternateKey { get; set; }
}
But I can't call this view in my repository. My repository code is bellow:
public class FactCousumptionRepository: GenericRepository<FactCousumption>, IFactCousumptionRepository
{
public DbContext _dbContext;
public FactCousumptionRepository(BaseDbContext context) : base(context)
{
_dbContext = context;
}
public async Task<FactALLCousumption> GetTotalAllCousumption()
{
}
}
In EF Core 2.2 or 2.1, you could use Query types.
According to the screenshot and the model to be used for the View you provided , I make a simple working demo like below , you could refer to and make the modification as per your demand:
1.Model
public class FactCousumption
{
public int Id { get; set; }
public double SumActiveImportTotal { get; set; }
public int DateKeyId { get; set; }
[ForeignKey("DateKeyId")]
public Dim_Date Dim_Date { get; set; }
public int TimeAltKeyId { get; set; }
[ForeignKey("TimeAltKeyId")]
public Dim_Time Dim_Time { get; set; }
public int TariffKeyId { get; set; }
[ForeignKey("TariffKeyId")]
public Dim_Tariff Dim_Tariff { get; set; }
}
public class Dim_Date
{
[Key]
public int DateKey { get; set; }
public int FullDateAlternateKey { get; set; }
public DateTime Date { get; set; }
public ICollection<FactCousumption> FactCousumptions { get; set; }
}
public class Dim_Time
{
[Key]
public int TimeAltKey { get; set; }
public DateTime Hour { get; set; }
public ICollection<FactCousumption> FactCousumptions { get; set; }
}
public class Dim_Tariff
{
[Key]
public int TariffType { get; set; }
public string TariffName { get; set; }
public ICollection<FactCousumption> FactCousumptions { get; set; }
}
2.Create SQL View
CREATE VIEW [dbo].[View1]
AS SELECT SUM(FactCousumption.SumActiveImportTotal) AS consumption ,Dim_Time.HOUR,Dim_Date.FullDateAlternateKey,Dim_Tariff.TariffName
FROM FactCousumption INNER JOIN
Dim_Date ON FactCousumption.DateKeyId = Dim_Date.DateKey INNER JOIN
Dim_Time ON FactCousumption.TimeAltKeyId=Dim_Time.TimeAltKey INNER JOIN
Dim_Tariff ON FactCousumption.TariffKeyId=Dim_Tariff.TariffType
GROUP BY Dim_Date.FullDateAlternateKey, Dim_Time.HOUR ,Dim_Tariff.TariffName
3.The model that is used for the view , note : the property name in model should be consistent with those in the view
public class FactALLCousumption
{
public double consumption { get; set; }
public DateTime hour { get; set; }
public int fullDateAlternateKey { get; set; }
}
4.DbContext , create a DbQuery property in my DbContext to consume the view results inside the Model and set up the View especially if you have different view name than your Class.
public DbQuery<FactALLCousumption> FactALLCousumption { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Query<FactALLCousumption>().ToView("View1");
}
5.Finally you can easily get the results of the View like this.
public async Task<FactALLCousumption> GetTotalAllCousumption()
{
var result = await _context.FactALLCousumption.FirstOrDefaultAsync();
return result;
}
Note: It's worth noting that DbQuery won't be/is not supported anymore in EF Core 3.0. See here
I have an Exercise entity defined in my ASP.NET MVC4 Web Application.
I'm using the Form Authentication with the default AccountModels.cs class.
I have class which looks like
public class Exercise
{
private DateTime _DateCreated = DateTime.Now;
private UserProfile _Teacher;
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public DateTime Date
{
get { return _DateCreated; }
set { _DateCreated = value; }
}
public UserProfile Author
{
get { return _Teacher; }
set { _Teacher = value; }
}
}
Am I using the UserProfile correctly to link between an Exercise and a logged in user?
How can I get the current UserProfile in my controller?
Change it like this:
public class Exercise
{
public Exercise()
{
this.Date = DateTime.Now;
this.Author = User.Identity.Name; //Write this line if you want to set
//the currently logged in user as the Author
public int Id{ get; set; }
public string Question { get; set; }
public int Anwser { get; set; }
public string Category { get; set; }
public int maxNbrOfAttempts { get; set; }
public string Hints { get; set; }
public virtual ICollection<Quiz> Quizzes { get; set; }
public virtual DateTime Date { get; set; }
public virtual UserProfile Author { get; set; }
}