How to match entities with stored procedure results(ASP.Net MVC with entity framework) - asp.net

I am calling one stored procedure which will takes 5 inputs and will returns a set of table data. I have created the class to match with the stored procedure results. How to map this stored procedure result with class?
My stored procedure will takes 6 parameters like below
PROC_REZ_GETCHNAVL 7012,3,20130816,20130817,1,'INR'
and it will gives the table set which will exactly same as below table.
public class AvailableRooms
{
[Required]
[Key]
public int CUSTCODE { get; set; }
public int CHANNID { get; set; }
public string RATECODE { get; set; }
public int RUNSRLNUB { get; set; }
public string ROOMTYPE { get; set; }
[Display(Name = "Room Name")]
public string ROOMNAME { get; set; }
public string ROOMSHTDESC { get; set; }
public string ROOMLNGDESC { get; set; }
public string ROOMFEATURES { get; set; }
public int MAXADT { get; set; }
public int MAXCHD { get; set; }
public int TOTROM { get; set; }
public char AVLFLG { get; set; }
public int AVLROM { get; set; }
public decimal OCCPER { get; set; }
public string RATETYPE { get; set; }
public string RATEPLAN { get; set; }
public string RATEDESCRP { get; set; }
public string RUNDAT { get; set; }
[Display(Name = "Room Rate")]
public decimal SGLRAT { get; set; }
public decimal DBLRAT { get; set; }
public decimal TRPRAT { get; set; }
public decimal QUDRAT { get; set; }
public decimal ADTRAT { get; set; }
public decimal CHDRAT { get; set; }
public decimal PLNSGLRAT { get; set; }
public decimal PLNDBLRAT { get; set; }
public decimal PLNTRPRAT { get; set; }
public decimal PLNQUDRAT { get; set; }
public decimal PLNEXTADTRAT { get; set; }
public decimal PLNEXTCHDRAT { get; set; }
public string ROOMIMG { get; set; }
public string PRPSHORTDESC { get; set; }
public string PRPLONGDESC { get; set; }
public string PRPFEATURES { get; set; }
public string TERMSCOND { get; set; }
public string CACELPOLICY { get; set; }
public string ROOMVID { get; set; }
public string CHANNELDESC { get; set; }
public int MAXPER { get; set; }
public int EXTPER { get; set; }
public int SEASONCODE { get; set; }
private decimal _SGLTOTRATE;
[DisplayFormat(DataFormatString = "{0:##,###}")]
public decimal SGLTOTRATE
{
get
{
return makeFormat(_SGLTOTRATE);
}
set
{
_SGLTOTRATE = value;
}
}
/// <summary>
/// Room Rate Currency Format
/// </summary>
/// <param name="_sglTotRate"></param>
/// <returns></returns>
private decimal makeFormat(decimal _sglTotRate)
{
if (_sglTotRate.ToString().Contains('.'))
_sglTotRate = Convert.ToDecimal(_sglTotRate.ToString("G29"));
return _sglTotRate;
}
public decimal DBLTOTRATE { get; set; }
public decimal EXTADTTOT { get; set; }
public decimal EXTCHDTOT { get; set; }
public decimal RACKSGL { get; set; }
public decimal RACKDBL { get; set; }
public decimal RACKADT { get; set; }
public decimal RACKCHD { get; set; }
public string MEALTYPE { get; set; }
public int DISSEQ { get; set; }
}
Please let me know how to map this class with stored procedure with DbContext?????
Awaiting for your resply.

Below is the solution for this.
namespace WBE.Repository
{
public class WBERepository : WBEContext,IWBERepository
{
/// <summary>
/// Get All the available rooms with respect to input parameters
/// </summary>
/// <param name="roomAvailInputs"></param>
/// <returns></returns>
public List<RoomInventory> GetRoomInventory(List<InventoryInputs> roomAvailInputs)
{
using (var context = new WBEContext())
{
var CustCode = new SqlParameter
{
DbType = DbType.Int32,
ParameterName = "CSTCOD",
Value = roomAvailInputs[0].CUSTCODE
};
var ChnlCode = new SqlParameter
{
DbType = DbType.Int32,
ParameterName = "CHNCOD",
Value = roomAvailInputs[0].CHNCOD
};
var ArrDate = new SqlParameter
{
DbType = DbType.String,
ParameterName = "ARRDAT",
Value = roomAvailInputs[0].ARRDAT
};
var DepDate = new SqlParameter
{
DbType = DbType.String,
ParameterName = "DEPDAT",
Value = roomAvailInputs[0].DEPDAT
};
var NoRooms = new SqlParameter
{
DbType = DbType.Int32,
ParameterName = "NBROOM",
Value = roomAvailInputs[0].NBROOM
};
var CurType = new SqlParameter
{
DbType = DbType.String,
ParameterName = "CURTYP",
Value = roomAvailInputs[0].CURTYP
};
return context.Database.SqlQuery<RoomInventory>
("PROC_REZ_GETCHNAVL #CSTCOD, #CHNCOD, #ARRDAT, #DEPDAT, #NBROOM, #CURTYP",
CustCode, ChnlCode, ArrDate, DepDate, NoRooms, CurType).ToList<RoomInventory>();
}

Related

List of items relate to two tables one contain foreign key other the primary key and check if item contain primary key is not in the database insert

I have task to get list of items which contain properties related to two tables(Item, PurchaseItemOrder), This list contain the Code property related to Item class this property is not the primary key for business reasons. So I have to search in the database by this Code and if this Item does not exist in the database insert it, And finally return the Id of the Item which is the primary key and get this key as foreign key in another table PurchaseItemOrder, I did some code, and I see this question Check if List of Items exist in database and if not Add it to database, but seems not exactly what I want can I do better?
Here May Code look like:
public class Item :Entity<int> , IFullAudited<User>
{
public string Name_en { get; set; }
public string Name_ar { get; set; }
public string Code { get; set; }
public string Description_en { get; set; }
public string Description_ar { get; set; }
public User CreatorUser { get; set; }
public User LastModifierUser { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public User DeleterUser { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
}
public class PurchaseOrderItem : Entity<int>, IFullAudited<User>
{
public int POId { get; set; }
public int Qty { get; set; }
public int ItemId { get; set; }
public virtual Item Item { get; set; }
public User CreatorUser { get; set; }
public User LastModifierUser { get; set; }
public long? CreatorUserId { get; set; }
public DateTime CreationTime { get; set; }
public long? LastModifierUserId { get; set; }
public DateTime? LastModificationTime { get; set; }
public User DeleterUser { get; set; }
public long? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public bool IsDeleted { get; set; }
public PurchaseOrder PurchaseOrder { get; set; }
}
public class PurchaseOrderItemDto : EntityDto<int>
{
public string PONumber { get; set; }
public List<ItemDto> Items { get; set; }
}
public class ItemDto :EntityDto<int>
{
public string Name_en { get; set; }
public string Name_ar { get; set; }
public string Code { get; set; }
public string Description_en { get; set; }
public string Description_ar { get; set; }
public int Qty { get; set; }
}
private int CheckPO(PurchaseOrderItemDto dto)
{
var poExist = _purchaseOrderRepository.FirstOrDefault(po => po.PONumber == dto.PONumber);
int id;
if (poExist == null)
{
id = _purchaseOrderRepository.InsertAndGetId(new PurchaseOrder
{
PONumber = dto.PONumber,
StatusId = 1
});
}
else
{
id = poExist.Id;
}
return id;
}
private int CheckItem(ItemDto itemDto)
{
var itemExist = _itemRepository.FirstOrDefault(it => it.Code == itemDto.Code);
int id;
if (itemExist == null)
{
id = _itemRepository.InsertAndGetId(new Item
{
Name_en = itemDto.Name_en,
Name_ar = itemDto.Name_en,
Code = itemDto.Code,
Description_en = itemDto.Description_en,
Description_ar = itemDto.Description_ar
});
}
else
{
id = itemExist.Id;
}
return id;
}
public void UploadPurchaseOrderItems(PurchaseOrderItemDto dto)
{
var poId = CheckPO(dto);
foreach (var poItem in dto.Items)
{
int itemId = CheckItem(poItem);
_repository.Insert(new PurchaseOrderItem
{
POId = poId,
Qty = poItem.Qty,
ItemId = itemId
});
}
}

How to modify database having foreign key in asp.net?

I have two tables: SurveyOption and SurveyQuestion, in my DbModel.
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}
public class SurveyQuestions
{
[Key]
public Guid SurveyQuestionsId { get; set; }
public Guid? SurveyMasterId { get; set; }
public int? Sequence { get; set; }
[MaxLength(1)]
public string QuestionType { get; set; }
[MaxLength(500)]
public string QuestionText { get; set; }
public bool? Required { get; set; }
public string ExplanationLink { get; set; }
}
SurveyQuestionId is the foreign key in SurveyOption. While making an update query I repeatedly get an error The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SurveyOptions_SurveyQuestions". The conflict occurred in database "MCNITemp", table "dbo.SurveyQuestions", column 'SurveyQuestionsId'.
My ViewModel of SurveyQuestion consist of OptionList. In which each SurveyQuestion holds its own optionList of type List<SurveyOption> and questionList is of type List<SurveyQuestion>
My modify code is the following:
foreach (var question in questionList)
{
var options = question.OptionsList;
foreach (var option in options)
{
var optionData = _mcniDbContext.SurveyOptions.Where(e => e.SurveyOptionId == option.SurveyOptionId).FirstOrDefault();
if (optionData == null)
{
_mcniDbContext.SurveyOptions.Add(new SurveyOptions()
{
OptionValue = option.OptionValue,
Description = option.Description,
Sequence = option.Sequence,
SurveyOptionId = option.SurveyOptionId,
SurveyQuestionId = option.SurveyQuestionId
});
}
else
{
optionData.SurveyOptionId = option.SurveyOptionId;
optionData.SurveyQuestionId = option.SurveyQuestionId;
optionData.Sequence = option.Sequence;
optionData.OptionValue = option.OptionValue;
optionData.Description = option.Description;
_mcniDbContext.Entry(optionData).State = EntityState.Modified;
}
_mcniDbContext.SaveChanges();
}
var questionData = _mcniDbContext.SurveyQuestions.Where(e => e.SurveyQuestionsId == question.SurveyQuestionsId).FirstOrDefault();
questionData.SurveyQuestionsId = question.SurveyQuestionsId;
questionData.SurveyMasterId = surveyMasterId;
questionData.QuestionText = question.QuestionText;
questionData.QuestionType = question.QuestionType;
questionData.Required = question.Required;
_mcniDbContext.Entry(questionData).State = EntityState.Modified;
_mcniDbContext.SaveChanges();
}
In your model you have let EF know how relationships are working. Assuming you have not used Fluent Api for desribing same, your code can be like below (code has not been test):
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
[ForeignKey("SurveyQuestionId")]
public SurveyQuestion SurveyQuestion {get;set;}
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}

Can't convert from model to viewmodel, using AutoMapper asp.net core

I am using Auto mapper to map between modelviews and models. I have followed the same steps given by the Auto mapper documentation and still can't find where the issue is.
public class RegisterStaffViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "StaffName Required")]
public string StaffName { get; set; }
[Required(ErrorMessage = "Gender Required")]
public string Gender { get; set; }
[Required(ErrorMessage = "Address Required")]
public string Address { get; set; }
[Required(ErrorMessage = "StaffCode Required")]
public string StaffCode { get; set; }
[DisplayName("Department")]
[Required(ErrorMessage = "Department is Required")]
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
[Required(ErrorMessage = "Mobileno Required")]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Wrong Mobileno")]
public string MobileNo { get; set; }
[Required(ErrorMessage = "EmailID Required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
public string Email { get; set; }
public DateTime EntryDate { get; set; }
[Display(Name = "Position")]
[Required(ErrorMessage = "Position is Required")]
public int? PositionId { get; set; }
[Display(Name = "Staff Type")]
[Required(ErrorMessage = "Staff Type is Required")]
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorderViewModel> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeavesViewModel> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
}
=============================================================================================
public partial class RegisterStaffs
{
public int Id { get; set; }
public string StaffName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string StaffCode { get; set; }
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
public DateTime EntryDate { get; set; }
public int? PositionId { get; set; }
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorder> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeaves> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
}
============================================================================================
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
});
return config.CreateMapper();
}
}
==========================================================================================
public async Task<ReturnResult<List<RegisterStaffViewModel>>> GetAllEmployees()
{
var result = new ReturnResult<List<RegisterStaff>>();
try
{
var employees = await context.RegisterStaffs.Where(x => (bool)!x.IsDeleted).OrderByDescending(x => x.EntryDate).AsNoTracking().ToListAsync();
// **here is the error**
result.Success(mapper.Map<List<RegisterStaffs>, List<RegisterStaffViewModel>>(employees));
}
catch(Exception ex)
{
}
return result;
}
============================================================================================
public class ReturnResult<T>
{
public ReturnResult()
{
ErrorList = new List<string>();
}
public bool IsSuccess { get; set; }
public HttpCode HttpCode { get; set; }
public T Data { get; set; }
public List<string> ErrorList { get; set; }
/// <summary>
/// Set success result with data
/// </summary>
/// <param name="Data"></param>
public void Success(T Data)
{
this.IsSuccess = true;
this.HttpCode = HttpCode.Success;
this.Data = Data;
}
/// <summary>
/// Set Server Error result with error message
/// </summary>
/// <param name="Error"></param>
public void ServerError(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.ServerError;
this.ErrorList.Add(Error);
}
/// <summary>
/// Set Not Found result with error message
/// </summary>
/// <param name="Error"></param>
public void NotFound(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.NotFound;
this.ErrorList.Add(Error);
}
}
I found the issue was here
var result = new ReturnResult<List<RegisterStaff>>();
i have changed it to
var result = new ReturnResult<List<RegisterStaffViewModel>>();

Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'

I am getting the following error
Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'
private CellSite MapEntityToCellSitePOCO(t_CellSite _cellsite)
{
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region.RegionId = _cellsite.RegionId;
return cellsite;
}
the following is my datacontracts file
public class CellSite
{
public Guid CellSiteID { get; set; }
public string SiteId { get; set; }
public Region Region { get; set; }
public Market Market { get; set; }
public Guid? ConstructionManager { get; set;}
}
This is market.cs
public class Market
{
public Guid? MarketID { get; set; }
public string OperatorMarketName { get; set; }
public string MarketName { get; set; }
public decimal AllOtherAmount { get; set; }
public decimal RawLandAmount { get; set; }
public decimal RenewalFee { get; set; }
public bool IsActive { get; set; }
}
there is a column MarketId in cellsite table which i want to bring on.how can i do that? I am new to entity frame work.
thanks in advance
You have to initialize your Market and Region properties first:
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market = new Market();
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region = new Region();
cellsite.Region.RegionId = _cellsite.RegionId;

Retrieving twitter with json

I'm having trouble with parsing a twitter flow, this code is returning this error message:
No parameterless constructor defined for type of
'System.Collections.Generic.IEnumerable`1[[Xxxx.Website.Templates.WidgetViews.Tweet,
Dolphin, Version=1.0.4801.24288, Culture=neutral,
PublicKeyToken=null]]'.
I would very much appreciate your help!
public partial class TwitterWidgetView
{
protected override void OnLoad(System.EventArgs e)
{
string listName = "sas";
string twitterListPath = "https://search.twitter.com/search.json?q=" + listName;
WebClient wc = new WebClient();
var json = wc.DownloadString(twitterListPath);
JavaScriptSerializer ser = new JavaScriptSerializer();
var tweetList = ser.Deserialize<IEnumerable<Tweet>>(json);
}
}
public class Metadata
{
public string result_type { get; set; }
}
public class Tweet
{
public Tweet()
{}
public string created_at { get; set; }
public string from_user { get; set; }
public int from_user_id { get; set; }
public string from_user_id_str { get; set; }
public string from_user_name { get; set; }
public object geo { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string iso_language_code { get; set; }
public Metadata metadata { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string source { get; set; }
public string text { get; set; }
public string to_user { get; set; }
public int to_user_id { get; set; }
public string to_user_id_str { get; set; }
public string to_user_name { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
}
public class RootObject
{
public RootObject()
{}
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_page { get; set; }
public int page { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public List<Tweet> results { get; set; }
public int results_per_page { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
Try using a list instead
var tweetList = ser.Deserialize<List<Tweet>>(json);

Resources