System.InvalidOperationException: Nullable object must have a value. Linq to sql - linq-to-sql

I am getting this error in one of my development machine. This error is not happening in other machine which is pointing to same database. Definitely both servers are not identical. I don't know what software which is missing in one server cause this issue. Both machine is running same OS 2008 R2.
using (MYDB.MyDB oDB = new MYDB.MyDB())
{
var query = from t in oDB.Products
where (_ProductId.HasValue?_ProductId==t.Productid:true)
select new Product()
{
ProductId = t.Productid,
ManufacturerId = t.Manufacturerid,
ManufacturingNumber = t.Manufacturingnumber,
CustomProduct = t.Iscustomproduct ? "Yes" : "No",
IsCustomProduct = t.Iscustomproduct,
SubCategoryName = t.Subcategory.Subcategoryname
};
return query.ToList();
}
Any help is highly appreciated
Thanks,
Senthilkumar

I can not reproduce the exception in a comparable case, but the part _ProductId.HasValue?_ProductId==t.Productid:true looks suspect. I would change it as follows and if you're lucky it also solves your problem, otherwise it's an improvement anyway:
var query = from t in oDB.Products;
if (_productId.HasValue)
{
query = query.Where(t => t.Productid == _productId.Value);
}
query = query.Select(t => new Product() {...
Another cause could be that Product.ProductId is not a nullable int.

Related

RedBean PHP credit card number issue

I have started using Redbean PHP recently. So I am not much aware of how it deals things.
Until now I love how simple it is making things for me. But I have ran into quite an issue today. I need to store credit card numbers into a table. But as soon as I store the bean, the card number gets changed into a float(decimal) kind of value.
'1234123412341234' is getting stored as '1.234123412341234e15'
The datatype is 'double' created by redbean, but I gave as a string. This is kind of weird for me I am not much of an expert in either SQL or PHP. Is there a way to override how redbean creates table. So someone please help me. Am I missing something here. The following is my corresponding code and the framework used is Codeigniter.
Data Variable
$data = array(
'card_name' => 'Shiva Kumar Avula',
'card_no' => '1234123412341234',
'card_issuer' => 'Visa',
'card_cvv' => '123',
'card_exp_month' => 12,
'card_exp_year' => 2020
);
$card = $this->card_model->create_card($data, TRUE); // Making it primary
Model Function
public function create_card($data, $is_primary = FALSE)
{
$card = R::dispense('card');
$card->name = $data['card_name'];
$card->number = $data['card_no'];
$card->issuer = $data['card_issuer'];
$card->cvv = $data['card_cvv'];
$card->exp_month = $data['card_exp_month'];
$card->exp_year = $data['card_exp_year'];
$card->is_primary = $is_primary;
$card->is_verified = 0;
$card->ts_created = $this->ts_sql;
$card->ts_modified = $this->ts_sql;
$id = R::store($card);
}
Snapshot of my output in phpmyadmin,
Snapshot that shows the datatype,
You can set the beans meta property for number to string.
$card->setMeta("cast.number", "string");
This will save any values of $card->number as varchar.
See RedBean Internals for more information.

CurrentUtcDateTime does not exist - Entity Framework and MySql

I am having a problem with canonical functions in Entity Framework 4.1 and MySql Connector/Net 6.4.3.
According to Microsoft cannonical functions are understood and translated into the local SQL dialect by all database providers from the SQL generated by LINQ; http://msdn.microsoft.com/en-us/library/bb738626.aspx However, my code chokes on CurrentUtcDateTime(), which is listed here; http://msdn.microsoft.com/en-us/library/bb738563.aspx
Here is the LINQ query (from NopCommerce) that generates the offensive SQL:
public List<Poll> GetPolls(int languageId, int pollCount, bool loadShownOnHomePageOnly)
{
bool showHidden = NopContext.Current.IsAdmin;
var query = (IQueryable<Poll>)_context.Polls;
if (!showHidden)
{
query = query.Where(p => p.Published);
query = query.Where(p => !p.StartDate.HasValue || p.StartDate <= DateTime.UtcNow);
query = query.Where(p => !p.EndDate.HasValue || p.EndDate >= DateTime.UtcNow);
}
if (loadShownOnHomePageOnly)
{
query = query.Where(p => p.ShowOnHomePage);
}
if (languageId > 0)
{
query = query.Where(p => p.LanguageId == languageId);
}
query = query.OrderBy(p => p.DisplayOrder);
if (pollCount > 0)
{
query = query.Take(pollCount);
}
var polls = query.ToList();
return polls;
}
query.ToList() generates the SQL below:
SELECT`Project1`.`PollID`, `Project1`.`LanguageID`, `Project1`.`Name`,
`Project1`.`Published`, `Project1`.`ShowOnHomePage`, `Project1`.`DisplayOrder`,
`Project1`.`SystemKeyword`, `Project1`.`StartDate`, `Project1`.`EndDate`
FROM (SELECT`Extent1`.`PollID`, `Extent1`.`LanguageID`, `Extent1`.`Name`,
`Extent1`.`SystemKeyword`, `Extent1`.`Published`, `Extent1`.`ShowOnHomePage`,
`Extent1`.`DisplayOrder`, `Extent1`.`StartDate`, `Extent1`.`EndDate`
FROM `Nop_Poll` AS `Extent1` WHERE ((((`Extent1`.`Published` = 1) AND
((`Extent1`.`StartDate` IS NULL) OR (`Extent1`.`StartDate` <= (CurrentUtcDateTime()))))
AND ((`Extent1`.`EndDate` IS NULL) OR (`Extent1`.`EndDate` >= (CurrentUtcDateTime()))))
AND (`Extent1`.`ShowOnHomePage` = 1)) AND (`Extent1`.`LanguageID` = #p__linq__0))
AS `Project1` ORDER BY `Project1`.`DisplayOrder` ASC LIMIT 2147483647
This is error is outputed:
*FUNCTION myDatabase.CurrentUtcDateTime does not exist
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: MySql.Data.MySqlClient.MySqlException: FUNCTION myDatabase.CurrentUtcDateTime does not exist*
Am I missing something? Please advice. Thanks.
I encountered this exact same problem and lost almost two days trying to figure it out. It appears to be a bug in the EntityFramework mappings for MySql.
The solution is to move the DateTime.UtcNow calculation outside of the scoped lambda and plug in the actual value.
var utcNow = DateTime.UtcNow;
query = query.Where(p => p.Published);
query = query.Where(p => !p.StartDate.HasValue || p.StartDate <= utcNow);
query = query.Where(p => !p.EndDate.HasValue || p.EndDate >= utcNow);
Based on Bohemian's suggestion, I fixed this issue with a "bypass" function.
CREATE FUNCTION `your_schema`.`CurrentUtcDateTime` ()
RETURNS TIMESTAMP DETERMINISTIC
RETURN UTC_TIMESTAMP();
Use UTC_TIMESTAMP()

LINQ To SQL does not work when adding new object

I use the following code to insert a new record to my Users table:
public bool CreateUser(User obj)
{
obj.Id = Guid.NewGuid();
using (_db = new CMSDataContext())
{
obj.SiteId = SiteID;
_db.Users.InsertOnSubmit(obj);
_db.SubmitChanges();
}
return true;
}
I do not get any errors, and everything seems fine. I can read a record from database with same DataContext. But after the above method runs completely, I see nothing new in my Users table. Why?
Is the id column truly a PK in the sql server database?

Can I update 1 object only with Linq to SQL?

Its a simple question, but I'm not aware of the answer and I couldn't get it to work.
Can I update only one entity on the entire DataContext? Or should I follow plain ADO.NET for this operation only?
Edit:
public MyObject GetMyObjectById(int selectedId)
{
DataContext db = _dbManager.GetContext();
return db.MyObject.SingleOrDefault(p => p.Id == selectedId);
}
I am getting an object with the above query...
I am querying then for an integer...on another table/object
public int GetMyInteger()
{
DataContext db = _dbManager.GetContext();
return db.MyAnotherObject.FirstOrDefault().MyInteger;
}
Everything is fine for all my operations...but now i just want to update only the integer i got from the database...
public void SetMyInteger(int updInteger)
{
DataContext db = new DataContext(ConnectionString);
MyAnotherObject theEntity = db.MyAnotherObject.FirstOrDefault();
atheEntity.MyInteger = updInteger;
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
The above method deleted MyObject i got from the first query!!! Of course if i use the static context DataContext tries to update MyObject and MyAnotherObject which seems the correct behaviour.
Edit:
I have changed the method getting the integer with a new datacontext as well and seems to working correctly, i have a strange thought on why called the delete method, because it was the method that was called, but again .. is working now...
Thank you all for your time.
Yes it's possible. What have you tried? It should be as simple as this:
using (var dc = new YourDataContext())
{
Person p = dc.Persons.Take(1).Single();
p.FirstName = "Ahmad";
dc.SubmitChanges();
}
Yes, you can:
Foo foo = dc.Foos.Where(foo => foo.Id == 345).Single();
foo.Name = "foo";
dc.SubmitChanges();

LINQ 2 SQL Query ObjectDisposed Exception

This one i had today is a strange one.
I have this query in an assembly method.
public Order[] SelectAllOrders()
{
Order[] orders;
using (MyDataContext context = new MyDataContext())
{
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(order => order.OrderDetails);
context.LoadOptions = dlo;
orders = context.Orders.Select(p => p).ToArray();
}
return orders;
}
Supposed i already called the ToArray() the SQL Command executed and gave me the objects i need and i give them to a new Order[] array this should not need the DataContext instance.
While im serializing the Order[] i get from the method return, serializer tries to access the DataContext again and i get an exception that cannot access disposed object.
Tried without the using() statement and works like it should. But, why i get this behavior?
Anyone could give an explanation why deferred loading still remains while I'm calling .ToArray() and assigning new variable with the contents?
The Select(p=>p) achieves very little; you might as well just call:
orders = context.Orders.ToArray();
Re the problem - I would guess that either OrderDetails hasn't really loaded, or it is trying to load some other data lazily. I would suggest investigating by (in a dev session):
Order[] orders;
using (MyDataContext context = new MyDataContext())
{
context.Log = Console.Out; // show me
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(order => order.OrderDetails);
context.LoadOptions = dlo;
Console.WriteLine("> Calling ToArray");
orders = context.Orders.ToArray();
Console.WriteLine("> ToArray complete");
// TODO: your extra code that causes serialziation, probably
// involving `DataContractSerializer`
Console.WriteLine("> Calling Dispose");
}
With this, you should be able to see any extra database trips that are happning after the ToArray but before the Dispose(). The point being: this data is needed for serialization, so either a: ensure it gets loaded, or b: exclude it from serialization.