handling null values in linq to sql - asp.net-mvc

i have to handle exception in my query when assigning values in view model ie i have set the values in view model when any value is null it is not showing other fields of my table showing error object reference error how to handle this error in my query
my code is as follows-
var query = (from results in db.Resumes
where results.ResumeID == ResumeID && results.User.UserID == uid
select results).ToList().Select(results=>new ResumewizardPreviewmodel
{
Resumetitle = results.ResumeTitle??"",
DesiredJob = results.DesiredJob??"",
Objective = results.Objective??"",
DesiredCompany = results.DesiredCompany??"",
DesiredSalary = results.DesiredSalary.ToString(),
Salarytype = results.SalaryType,
additionalinfo = results.AdditionalInfo,
res_url = results.Res_URL,
visa = results.Visa.ToString()??"0",
TelecommuteType = results.TelecommuteType.Description,
RelocationType = results.RelocationType.Description,
isactive = results.IsActive,
isConfidential = results.isConfidential
}).SingleOrDefault();

You can use a tool like AutoMapper to convert one entity to another.
Here is an example of converting collections and null value substitution.

Related

Entity Framework: Select field name causing error

The moment I mention field names when fetching data from db, I start getting errors.
Before my code was this and it was working:
var customer = from s in db.Customers
select s;
The moment I change it to:
var customer = (from s in db.Customers
select new
{
CompanyName = s.CompanyName,
ContactName = s.ContactName,
ContactTitle = s.ContactTitle,
Address = s.Address,
});
I start getting error as follows:
The model item passed into the dictionary is of type
'PagedList.PagedList1[<>f__AnonymousType24[System.String,System.String,System.String,System.String]]',
but this dictionary requires a model item of type
'PagedList.IPagedList`1[MVCCRUDPageList.Models.Customer]'.
My view looks like:
#model PagedList.IPagedList<MVCCRUDPageList.Models.Customer>
#using PagedList.Mvc;
This error is caused because you are not sending the Customer model to the view.
By doing select new { ... } you are creating an anonymous object.
You may consider changing your code to:
select new MVCCRUDPageList.Models.Customer
{
CompanyName = s.CompanyName,
ContactName = s.ContactName,
ContactTitle = s.ContactTitle,
Address = s.Address,
}
You may still need to convert the IQueryable to IPagedList
The error is telling you that the view is expecting one type but you are passing it another type. The Linq Select method you have is projecting to an anonymous type instead of the expected Customer class. Change your code to match, something like this
var customer = (from s in db.Customers
select new Customer //<--- This here, you may need to use
// the full namespace MVCCRUDPageList.Models
{
CompanyName = s.CompanyName,
ContactName = s.ContactName,
ContactTitle = s.ContactTitle,
Address = s.Address,
});

Get list of instances, Grails

I need to get list of instances. I did so to do this:
def availableCafee = Cafee.list()
But now, my task is complicated. It requires if certain field in instance doesn't have an empty string value, other fields of the instance must be found via some controller and the other instance by this string value. Domain class is below.
If apiInit is empty, the instance added to list how in example above, if apiInit isn't empty, it assumed other fields wasn't initialized, so getting other fields requires via controller, which I've done and the other instance.So external API work is emulate. How to change example above to do this?
class Cafee {
String cafeeName = ""
int totalReservationPlaces = 0
double placeCost = 0
String currencyType = ""
boolean isReservationAvailable = false
boolean reservationTimeLimit = false
boolean reservationDateLimit = false
int totalPlaces = 0
LocalTime startTimeLimit = new LocalTime()
LocalTime endTimeLimit = new LocalTime()
Date startDateLimit = new Date()
Date endDateLimit = new Date()
String region = ""
String city = ""
String apiInit = ""
}
I think what you are trying to say is that a nullable object is causing the object not to be saved.
The solution is quite simple:
static constraints = {
apiInit nullable: true
}
Have a read here: rejected-value-null
So ideally set all those objects that are could be nullable should be set
ChatUser.groovy
you can also set the defaultValue of an object in the mapping:
MailingListBase.groovy
Please note if it is an already generated Database table any attempt now to set to nullable after it has been previously created will not work. you will either have to set this manually or drop it and let it regenerate..

Groovy Dynamic Object - How to properly reset properties?

Based on this question I created a Groovy class that will have dynamic properties.
class MyDynamic {
def propertyMissing( String name, value ) {
this.metaClass."$name" = value
value
}
}
So far all good, now I can set some non-existent property with success
MyDynamic dyna = new MyDynamic()
dyna.someProp = new Date()
My problem begins when I have another instance with the same name of property, but with another type
MyDynamic dyna2 = new MyDynamic()
dyna2.someProp = "0" //GroovyCastException: Cannot cast object '0' with class 'java.lang.String' to class 'java.util.Date'
Actually I need this because I'm creating objects with the result of a query without knowing the table and the column. I get the name of the column with the ResultSetMetaData and add the property to the instance of the dynamic object. Later I will use this object to export all the properties and values. In different tables I have the same column name, but with different types.
So my question is: how can I reset this metaClass when I'm done with the instance to not conflict with other instance?
Why not a Expando, a Map or a simple container:
class Dynamic {
def properties = [:]
void setProperty( String name, value ) {
properties[name] = value
}
def getProperty(String property) { properties[property] }
}
d = new Dynamic()
d.name = "yeah"
assert d.name.class == String
d.name = new Date()
assert d.name.class == Date

How to parse multiple nodes of html using HtmlAgilityPack?

I'd appreciate if someone could help! I'm trying to parse the following page of Groupon website http://www.groupon.com/browse/chicago?category=activities-and-nightlife
var webGet = new HtmlWeb();
var deal1 = webGet.Load("http://www.groupon.com/browse/chicago?category=activities-and-nightlife");
I want to get the whole block of each Deal(i.e. offer for discount)
HtmlNodeCollection content_block = deal1.DocumentNode.SelectNodes("//div[#class = 'deal-list-tile grid_5_third']");
Then out of each block i want to get title, company name, location and price.
foreach(HtmlNode node in content_block)
{
string title2 = node.SelectSingleNode("//div[#class = 'deal-title js-permalink']").InnerText;
string country2 = node.SelectSingleNode("//p[#class = 'merchant-name']").InnerText;
string location2 = node.SelectSingleNode("//p[#class = 'location']").InnerText;
string price2 = node.SelectSingleNode("//div[#class = 'price']/span").InnerText;
}
Here i get confused, i need to write all the information about deals into
DbSet<Deal> Deals , but even if i try to display the content as ViewBag.Message = title + country + location + price; i get System.NullReferenceException: Object reference not set to an instance of an object in the line with content_block.
What am i doing wrong =(
Thanks in advance!
The problem appears to be that the selectnodes returns nothing or null when no nodes are found instead of an empty collection. so this means you should probably wrap if (content_block != null) { around your code block above.

LINQ Checking for Nulls

How do I check Nulls in Linq?
I have a third-party code that returns a DataTable with a column type DateTime that is nullable.
My code:
var profile = (from d in ds.Tables[0].AsEnumerable()
select new User
{
FirstName = d["FirstName"].ToString(),
Birthdate = Convert.ToDateTime(d["BirthDate"].ToString())
}).FirstOrDefault();
returns an error that the Object cannot be cast from DBNull to other types on the Birthdate= statement.
I tried using the following code but returns a cast exception (Cannot cast from string to DateTime?)
Birthdate = (DateTime?)d["BirthDate"].ToString();
Is there a way to short-hand checking the null values?
I have not tested this, but you can try the following:
Birthdate = d.Field<DateTime?>("BirthDate")
From MSDN:
The Field method provides support for accessing columns as nullable types. If the underlying value in the DataSet is [DBNull.]Value, the returned nullable type will have a value of null.
You can create a helper function to check the value for DBNull, as follows:
private static DateTime? ConvertNullableToDateTime(object val) {
return (val != null && val != DBNull.Value) ? Convert.ToDateTime(val.ToString()) : null;
}
Now you can use this method in your LINQ query:
var profile = (from d in ds.Tables[0].AsEnumerable()
select new User
{
FirstName = d["FirstName"].ToString(),
Birthdate = ConvertNullableToDateTime(d["BirthDate"])
}).FirstOrDefault();
I have got error while I used the above code. I think we can use the below code.
Birthdate = dr["BirthDate"] == DBNull.Value ? (DateTime?)null : (DateTime)dr["BirthDate"];
If we use Convert.ToString(dr["BirthDate"]), then it convert to empty string, if it has DBNull.
Try that also.

Resources