I created my database with entity framework - code first.
public class Customer:BaseEntity
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string VerPassword { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public int RolId { get; set; }
public int QR { get; set; }
}
I have a working registration page but know I added QR part which is integer. I do not want to user give any input for this and I want it to be NULL in the database.
I set all of the datas to database with this design pattern
_customerService.Add(model);
I tried to set null to QR column like this but it does not work
int? value = 0;
if (value == 0)
{
value = null;
}
model.QR = value;
The error is "Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)"
What can I do to set null value to QR column
What can I do to set null value to QR column
int does not allow null's, so you need to change QR type to be a nullable int (i.e. int? or Nullable<int>):
public class Customer:BaseEntity
{
// ...
public int? QR { get; set; }
}
Read more:
Nullable value types
Related
I have this proto file
syntax = "proto3";
message AdminIpoChange
{
string Id =1;
string SymbolName =2;
string SymbolIsin =3;
string Date =4;
string Time=5;
double MinPrice =6;
double MaxPrice =7;
int32 Share =8;
bool Show =9;
AdminIpoOperation Operation =10;
string CreateDateTime=11;
enum AdminIpoOperation
{
Add = 0;
Edit = 1;
Delete = 2;
}
}
And here I have this class
public class AdminIpoChangeEntity : BaseEntity
{
public AdminIpoChangeEntity()
{
}
public string SymbolName { get; set; }
public string SymbolIsin { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public double MinPrice { get; set; }
public double MaxPrice { get; set; }
public int Share { get; set; }
public bool Show { get; set; }
public AdminIpoOperation Operation { get; set; }
public DateTime CreateDateTime { get; set; }
public enum AdminIpoOperation
{
Add = 0,
Edit = 1,
Delete = 2
}
}
So I want to convert the operation enum in proto to enum in c# as you can see :
public static AdminIpoChangeEntity Map(AdminIpoChange adminIpoChange)
=> new()
{
CreateDateTime=DateTime.Parse(adminIpoChange.CreateDateTime),Date=adminIpoChange.Date,MaxPrice=adminIpoChange.MaxPrice,
MinPrice=adminIpoChange.MinPrice,Operation=adminIpoChange.Operation,Share=adminIpoChange.Share,Show=adminIpoChange.Show,
SymbolIsin=adminIpoChange.SymbolIsin,SymbolName=adminIpoChange.SymbolName,Time=adminIpoChange.Time,
};
But in this part Operation=adminIpoChange.OperationI get this error :
Severity Code Description Project File Line Suppression State
Error CS0266 Cannot implicitly convert type 'AdminIpoChange.Types.AdminIpoOperation' to 'domain.Entities.AdminIpoChangeEntity.AdminIpoOperation'. An explicit conversion exists (are you missing a cast?) domain D:\****\domain\Entities\AdminIpoChangeEntity.cs 43 Active
I'm trying to read a flat file and do some processes. To do that I've defined a mapper. That mapper will assign the values for each property. In the document, the date will be represented with yyMMdd format and it can have "" or 000000 as a null value. That mean, if the date is 6 zeros or 6 blank spaces, the output should be null. I tried to do this by defining a NullFormater. But didn't work.
This is what I've tried:
============================
public class Test : DocumentRecordBase
{
public string StorageOrganisation { get; set; }
public Guid? StorageOrganisationId { get; set; }
public string StorageDescription { get; set; }
public DateTime? PaymentDueDate { get; set; }
public decimal? DiscountRate { get; set; }
public int? MaximumDaysDiscount { get; set; }
public DateTime? DateStorageChargeCommences { get; set; }
public decimal? StorageChargePerBalePerDay { get; set; }
public decimal? PenaltyInterestRate { get; set; }
public DateTime? LotAvailableDate { get; set; }
public decimal? PostSaleRechargeRebate { get; set; }
public Test() : base()
{
}
public override T GetDocumentRecord<T>()
{
if (typeof(T) == typeof(Test))
{
return this as T;
}
return null;
}
public static IFixedLengthTypeMapper<Test> GetMapper()
{
var mapper = FixedLengthTypeMapper.Define<Test>();
mapper.Property(r => r.RecordType, 2);
mapper.Property(r => r.RecordSubType, 1);
mapper.Property(r => r.PaymentDueDate, 6)
.ColumnName("PaymentDueDate")
.InputFormat("yyMMdd")
.NullFormatter(NullFormatter.ForValue("000000")); // if the read value is "000000" or " " then should pass as null
mapper.CustomMapping(new RecordNumberColumn("RecordNumber")
{
IncludeSchema = true,
IncludeSkippedRecords = true
}, 0).WithReader(r => r.RecordNumber);
return mapper;
}
public static bool GetMapperPredicate(string x)
{
return x.StartsWith("11A");
}
}
According to the definition of NullFormatter, (found here), you can only assign 1 fixed value. "If it is a fixed value, you can use the NullFormatter.ForValue method."
NullFormatter = NullFormatter.ForValue("NULL")
If you use "000000", then it should convert 000000 to null otherwise, spaces will be considered actual values. Any number of 0s != 6 will result in non-null value as well.
Also, please define what you mean by "But didn't work". Please provide details and errors for elaboration
I am using dapper and I want to use Linq to be able to update a single field called status in one table I am trying to use.
public async Task<Int32> ProcessUnprocessedTransactions(IEnumerable<BomComponentData> items)
{
IEnumerable<BomComponentData> _itemstoBeProcesed = items.Where(w => w.Status == (int)BomStatus.Scanned);
foreach (BomComponentData item in _itemstoBeProcesed)
{
item.Status = (int)BomStatus.Completed;
}
return await database.UpdateAsync(_itemstoBeProcesed);
}
My class is as follows:
public class BomComponentData
{
public int Sequence { get; set; }
public string BOMShortName { get; set; }
public string OperationName { get; set; }
public long BomId { get; set; }
public long BOMLineID { get; set; }
public long StockItemID { get; set; }
public string BomLineType { get; set; }
public int Quantity { get; set; }
public long UnitID { get; set; }
public decimal? MultipleOfBaseUnit { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Barcode { get; set; }
public long ProductGroupID { get; set; }
public string ProductGroupCode { get; set; }
public int Status { get; set; }
public int BinLocation { get; set; }
public string BinName { get; set; }
public string UOM { get; set; }
public int CalculatedValue { get; set; }
public int BomPickedCount { get; set; }
public int TotalLeftTopick
{
get { return Quantity - BomPickedCount; }
}
public enum BomStatus
{
Listed=1,
Scanned=2,
Confirmed=3,
Processed=4,
Completed=4,
InVisible=5
}
public override string ToString()
{
return Code;
}
}
But it does not work if I use a foreach like above. I am sure it should update the items properly but I think that because I'm going through singular items in my foreach and my list in the update it's not updating correct.
All I want to do is mark the items as completed and ready for transfer, I am doing so by the status column and an int enum.
Maybe I am missing a declaration of what is my primary key?
Edit 2
When I use a key declaration of the primary key I get the following:
Unhandled Exception: System.AggregateException: One or more errors occurred. (Constraint
Edit 3
I have set key of my class but as you see I have auotincrement on my db and it still crashes. How should insert be handled?
Edit 4
For example I am inserting into the database as follows. Shouldn't this work?
List<BomComponentData> _bomList = new List<BomComponentData>();
_bomList.Add(new BomComponentData { Sequence = 1, Barcode = "0000000001498", BinLocation = 23, BinName = "A", BOMShortName = "GYNE-TXX", OperationName = "Example Product", Code = "TB9175CEA", Name = "Tiburon Peri/Gynae Pack-10", Quantity = 1, UOM = "Each" });
await database.InsertAllAsync(_bomList,true);
I have placed the tag key for the update that works ok but when I attempt to do an insert with the key it doesn't it says constraint error but the update works. Does anybody no how i can solve both the insert and update in Dapper contrib.
You are using Dapper.Contrib and this extension requires that you decorate your class with some attributes to help in the automatic handling of your data.
In particular for an Update method you need to define the Table attribute and the Key attribute to identify the primary key
[Table ("BomComps")]
public class BomComponentData
{
// [ExplictKey]
[Key]
public int Sequence { get; set; }
....
Here, for example, I have added the attribute Table to set a possible table name on the database, but if the name of the physical table matches the name of the class then you can omit the attribute. Also I have added the Key attribute to set the property that contains the primary key of your table (so the statement that updates your records could be formed with the proper WHERE condition).
Notice that the Key attribute should be used if the column has an Identity property set to yes while, if not, you use the ExplicitKey attribute to signal that the primary key is defined by your code.
This was actually the issue I had to decoate my class with the following Leaving this here so that anyone else has issue I was using the pcl libary but for some reason dapper contribe did not detect the key element it had to be declared as follows.
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public class StockTransferArgs
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int StockTransferArgsId { get; set; }
public long StockItemID { get; set; }
public string Code { get; set; }
public string OperationName { get; set; }
public string Description { get; set; }
public decimal Quantity { get; set; }
public long SourceWarehouseID { get; set; }
public string SourceBinName { get; set; }
public long TargetWarehouseID { get; set; }
public string TargetBinName { get; set; }
public string Reference { get; set; }
public string SecondReference { get; set; }
public string BarCode { get; set; }
public int Status { get; set; }
}
I have the following table
public class QTable
{
public string QID { get; set; }
public string QNO { get; set; }
public string Q1 { get; set; }
public string Q2 { get; set; }
public string opt1 { get; set; }
public string opt2 { get; set; }
public string opt3 { get; set; }
public string opt4 { get; set; }
public string Answer { get; set; }
public string Remarks { get; set; }
public string KnowledgeArea { get; set; }
public string Hints { get; set; }
public string Section { get; set; }
public string ToughLevel { get; set; }
public string DateCreated { get; set; }
public string Category { get; set; }
public string DeleteMe { get; set; }
}
QID is my primary key.
I have the
List<Qtable> qtableList = <list of all values of qtable from a query>
I need to find a particular QID and take other fields for manipulation.
Is there a SQL statement like structure to manipulate these things for a list?
You can use to get the item you want
Qtable item = qtableList.FirstOrDefault(x=>x.QID == id);
Just be aware that if the QID dont exists on the list and you try to access one of its properties, an 'Object reference is not an instance of an object exception' will be thrown, since you are trying to access a null object.
To prevent that, check if the return is differente of null prior to access and modify the properties you want.
In C# the best sql ike approach is just simply use linq, it's maded to handle this kind of request.
The basic syntax is:
var query = from qt in qtableList
where qt.QID == "1"
select qt;
This is basically returning the first pk element of your data.
Insert, update and other basic sql operations working as well.
More about on this:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations
I'm new to Entity Framework, I already searched in google for this problem but I found nothing. I get the error
An error occurred while updating the entries. See the inner exception for details.
and when I checked the inner exception, I see this
Cannot insert the value NULL into column 'DOCNUM', table 'TCPIDBV2.dbo.tbl_200_Dailyreport'; column does not allow nulls. INSERT fails.
But when I checked the records that I passed in to be saved in the database, there is a value in that object called 'DOCNUM'
This is my code:
[Table("tbl_200_Dailyreport")]
public class tbl_200_Dailyreport
{
[Key]
[Required]
public long DOCNUM {get; set;}
public DateTime DAILYREPDATE {get; set;}
public string SECTION {get; set;}
public string REMARKS { get; set; }
public int? OPERATIONTIME { get; set; }
public int? PREPARATIONTIME { get; set; }
public int? STANDBYTIME { get; set; }
public int? MATERIALWAITING { get; set; }
public int? ASSISTTIME { get; set; }
public int? MAINTENANCETIME { get; set; }
public int? CLEANINGTIME { get; set; }
public bool? ISOVERTIME { get; set; }
public bool? ISLOCKED { get; set; }
public string SHIFT { get; set; }
public int? PRODTIME { get; set; }
public int? BREAKTIME { get; set; }
public double? TOTALCOLOR { get; set; }
public double? AVERAGECOLOR { get; set; }
}
In getting a value of those above here is the code:
tbl_200_Dailyreport.DOCNUM = long.Parse(txtReferenceNo.Text);
tbl_200_Dailyreport.PRODTIME = Convert.ToInt32(txtProduction.Text);
tbl_200_Dailyreport.OPERATIONTIME = Convert.ToInt32(txtOperation.Text);
tbl_200_Dailyreport.PREPARATIONTIME = Convert.ToInt32(txtPreparation.Text);
tbl_200_Dailyreport.STANDBYTIME = Convert.ToInt32(txtStandby.Text);
tbl_200_Dailyreport.MAINTENANCETIME = Convert.ToInt32(txtMaintenance.Text);
tbl_200_Dailyreport.CLEANINGTIME = Convert.ToInt32(txtCleaning.Text);
tbl_200_Dailyreport.MATERIALWAITING = Convert.ToInt32(txtMaterial.Text);
tbl_200_Dailyreport.ASSISTTIME = Convert.ToInt32(txtAssist.Text);
tbl_200_Dailyreport.BREAKTIME = Convert.ToInt32(txtOthers.Text);
tbl_200_Dailyreport.DAILYREPDATE = dtpDailyReportDate.Value;
tbl_200_Dailyreport.SHIFT = cboShift.SelectedValue.ToString();
tbl_200_Dailyreport.ISOVERTIME = cbxOvertime.Checked;
tbl_200_Dailyreport.ISLOCKED = false;
tbl_200_Dailyreport.REMARKS = txtRemarks.Text;
if (!String.IsNullOrEmpty(cboSecDepartment.Text))
{
tbl_200_Dailyreport.SECTION = cboSecDepartment.SelectedValue.ToString();
}
else
{
var section = "0";
tbl_200_Dailyreport.SECTION = section;
}
I allow all of the column to null except the PK called the 'DOCNUM', so in getting the value of 'DOCNUM', where the txtreferenceno.Text has a value that is equal to 1 . and passed it in DailyReportManager so here's the code:
public void Save(tbl_200_Dailyreport records)
{
try
{
this.db.tbl_200_Dailyreport.Add(records);
this.db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
and in getting the value of txtreferenceno.Text
var max = dailyreportmanager.FindAll().Max(x => (int?)x.DOCNUM) ?? 0;
var addMax = max + 1;
txtReferenceNo.Text = Convert.ToString(addMax);
so for the design of my database
Allow me to post a screenshot:
Database Design
When I checked the records, the 'DOCNUM' has a value equals to one, but why did I still get that error? Please help. A big thanks in advance.
To indicate to Entity Framework that you want to manually specify the key value, specify this attribute:
[DatabaseGenerated(DatabaseGeneratedOption.None)]
against DOCNUM.