public ActionResult Index()
{
testEntities6 devicesEntities = new testEntities6();
List<DevicesModel> devicesModel = new List<DevicesModel>();
var device_query = from d in devicesEntities.device
join dt in devicesEntities.devicetype on d.DeviceTypeId equals dt.Id
join l in devicesEntities.location on d.Id equals l.DeviceId
join loc in devicesEntities.locationname on l.LocationNameId equals loc.Id
where l.DeviceId == d.Id
select new {
//devices
d.Id,
d.DeviceTypeId,
d.SerialNumber,
d.FirmwareRev,
d.ProductionDate,
d.ReparationDate,
d.DateOfLastCalibration,
d.DateOfLastCalibrationCheck,
d.CalCertificateFile,
d.Notes,
d.TestReportFile,
d.WarrantyFile,
d.CertificateOfOriginFile,
d.QCPermissionFile,
d.Reserved,
d.ReservedFor,
d.Weight,
d.Price,
d.SoftwareVersion,
//devicetype
dt.Name,
dt.ArticleNumber,
dt.Type,
//location
l.StartDate, //AS LastStartDate,
l.LocationNameId,
//locationname
Loc_name = loc.Name //AS CarrentLocation
};
foreach (var dv in device_query) {
devicesModel.Add(new DevicesModel(
//device
DeviceTypeId = dv.DeviceTypeId,
/*Why I have this error: The name 'DeviceTypeId' does not exist in the current context*/
...
));
}
return View(devicesModel);
}
Model:
public class DevicesModel
{
//device
public int deviceTypeId;
public int id;
public int serialNumber;
public string firmwareRev;
public DateTime productionDate;
public DateTime reparationDate;
public DateTime dateOfLastCalibration;
public DateTime dateOfLastCalibrationCheck;
public int calCertificateFile;
public string notes;
public int testReportFile;
public int warrantyFile;
public int certificateOfOriginFile;
public int qCPermissionFile;
public int BReserved;
public string reservedFor;
public double weight;
public int price;
public string softwareVersion;
//devicetype
public string name;
public string qrticleNumber;
public string type;
//location
public DateTime startDate;
public int locationNameId;
//locationname
public string loc_name;
public DevicesModel(){}
//device
public int DeviceTypeId{get;set;}
public int Id { get; set; }
public int SerialNumber { get; set; }
public string FirmwareRev { get; set; }
public DateTime ProductionDate { get; set; }
public DateTime ReparationDate { get; set; }
public DateTime DateOfLastCalibration { get; set; }
public DateTime DateOfLastCalibrationCheck { get; set; }
public int CalCertificateFile { get; set; }
public string Notes { get; set; }
public int TestReportFile { get; set; }
public int WarrantyFile { get; set; }
public int CertificateOfOriginFile { get; set; }
public int QCPermissionFile { get; set; }
public int bReserved { get; set; }
public string ReservedFor { get; set; }
public double Weight { get; set; }
public int Price { get; set; }
public string SoftwareVersion { get; set; }
//devicetype
public string Name { get; set; }
public string ArticleNumber { get; set; }
public string Type { get; set; }
//location
public DateTime StartDate { get; set; }
public int LocationNameId { get; set; }
//locationname
public string Loc_name { get; set; }
}
Its because you're creating an anonymous object in your linq "Select" clause. I think you want to create an instance of your DevicesModel class, e.g.
...
where l.DeviceId == d.Id
select new DevicesModel {
//devices
Id = d.Id,
...
I think you intend to use curly brackets instead of round brackets.
new DevicesModel
{
//device
DeviceTypeId = dv.DeviceTypeId,
...
}
or are you trying to use named arguments in C#4?
Related
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
});
}
}
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
What is the best solution to save correctly my database :
I want to save this datas in my sqlite databse and export it in CSV, i made a little method, but with this process i can't get the PhotoEnt in my EmailEntity.
PhotoEntity :
public class PhotoEntity : EntityBase
{
[PrimaryKey, AutoIncrement]
public override int Id { get; set; }
public string IdGuid { get; set; }
public string PhotoDate { get; set; }
public string Image { get; set; }
[OneToMany]
public List<EmailEntity> Emails { get; set; }
}
EmailEntity :
public class EmailEntity : EntityBase
{
[PrimaryKey, AutoIncrement]
public override int Id { get; set; }
[ForeignKey(typeof (PhotoEntity))]
public string IdGuid { get; set; }
public string Email { get; set; }
[ManyToOne]
public PhotoEntity PhotoEnt { get; set; }
}
And, when i saved, i do this :
private void DoInsertBddCommand()
{
var guidForId = Guid.NewGuid().ToString();
var dateTime = DateTime.Now.ToString();
var photoEntity = new PhotoEntity
{
IdGuid = guidForId,
Image = _imageName,
PhotoDate = dateTime
};
new PhotoBusiness().Save(photoEntity);
foreach (var item in Emails)
{
var emailEntity = new EmailEntity
{
IdGuid = guidForId,
Email = item,
PhotoEnt = photoEntity
};
new EmailBusiness().Save(emailEntity);
}
}
It's my first time with SQLite.net, any suggestion ?
Thank you
Okay, so here is how I would setup your models:
public class PhotoEntity : EntityBase
{
[PrimaryKey, AutoIncrement]
public override int Id { get; set; }
public string PhotoDate { get; set; }
public string Image { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<EmailEntity> Emails { get; set; }
}
public class EmailEntity : EntityBase
{
[PrimaryKey, AutoIncrement]
public override int Id { get; set; }
[ForeignKey(typeof (PhotoEntity))]
public int PhotoEntityId { get; set; }
public string Email { get; set; }
[ManyToOne(CascadeOperations = CascadeOperation.All)]
public PhotoEntity PhotoEnt { get; set; }
}
Notice that I define the cascade operations in the relationship attribtues. This is directly from the SQLite-Extensions docs: https://bitbucket.org/twincoders/sqlite-net-extensions#markdown-header-cascade-operations
Now when you save/retrieve objects you need to use the recursive methods:
GetWithChildren
InsertWithChildren
https://bitbucket.org/twincoders/sqlite-net-extensions#markdown-header-cascade-read
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>();
}
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);