Constructing or initializing instances of the type with the expression (<expression> == null) is not supported - odata

I am accessing OData API using ODataConnectedService.
When I use this code;
UpcomingJobsItems = context.EventStaffRequired
.Select(c => new UpcomingJob
{
EventType = c.Event.EventType == null ? "" : c.Event.EventType.Type,
});
I am getting below error;
System.NotSupportedException: 'Constructing or initializing instances
of the type UpcomingJob with the expression (c.Event.EventType ==
null) is not supported.'
If I don't check for null I get error on null values. How can I handle null values in this case?
Thanks
Regards

Related

How to log Exception.data key / values with Serilog 2?

Our legacy logging framework (.NET 4.5) would iterate over Exception.data and log each one of the Exception.data key values. It is nice for logging contextual props related to the current exception. Is there a way to configure Serilog to log the Exception.data key values?
Serilog 2
This is the equivalent code for Serilog:
public class ExceptionDataEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (logEvent.Exception == null ||
logEvent.Exception.Data == null ||
logEvent.Exception.Data.Count == 0) return;
var dataDictionary = logEvent.Exception.Data
.Cast<DictionaryEntry>()
.Where(e => e.Key is string)
.ToDictionary(e => (string)e.Key, e => e.Value);
var property = propertyFactory.CreateProperty("ExceptionData", dataDictionary, destructureObjects: true);
logEvent.AddPropertyIfAbsent(property);
}
}
You can find a complete program with configuration in this Gist.
A more sophisticated and flexible option is to use the Serilog.Exceptions package, which has smarts for a number of common exception types.

ASP.NET LINQ MULTIPLE OR IN WHERE

I have following code in asp.net core using multiple or in where statement. it always propmt error saying "An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
lambda_method"
if (!String.IsNullOrEmpty(searchString))
{
mTickets = from mt in mTickets
where
(mt.TicketServiceFullNo.Contains(searchString)) || (mt.DeviceNo.Contains(searchString)) select mt;
}
return View(await mTickets.AsNoTracking().ToListAsync());
However, If i just use one or condition in where. it will work. I have no idea why. Please help. thanks
this will work
if (!String.IsNullOrEmpty(searchString))
{
mTickets = from mt in mTickets
where
(mt.TicketServiceFullNo.Contains(searchString)) select mt;
}
return View(await mTickets.AsNoTracking().ToListAsync());
It's almost certain that mt.DeviceNo is null.
You'll need to replace:
(mt.DeviceNo.Contains(searchString))
with
(mt.DeviceNo != null && mt.DeviceNo.Contains(searchString))
or
(mt.DeviceNo?.Contains(searchString))
if you're using C# 6.0

"System.NullReferenceException" for Using Session in MVC

In My MVC project, I am using session values like
var empId = Convert.ToInt32(Session["EmpId"].ToString());
I am getting Exception:
"An exception of type 'System.NullReferenceException' occurred in Project.Web.dll but was not handled in user code.
Additional information: Object reference not set to an instance of an object."
This error occurs when you call a method on the null object. In your case the value of Session["EmpId"] is NULL.
Which means you are calling NULL.ToString(), which is invaild hence it throws error.
You can avoid the error using null coaleascing operator or simply check null before performing any opearation on it.
Solution:
if(Session["EmpId"] == null)
//do something
else
var empId = Convert.ToInt32(Session["EmpId"].ToString());
Alternatively you can check my blog post on it
Before use first check is it null or not.
var empId = Session["EmapId"] != null ? Convert.ToInt32(Session["EmapId"]) : 0;
You have to check null as shown below :-
var empId = Convert.ToInt32((Session["EmpId"] ?? 0).ToString());
A more efficient way to accomplish your requirement :-
int temp = 0;
var empId = int.TryParse( Convert.ToString( Session["EmpId"] ),out temp );

Error .The entity type List`1 is not part of the model for the current context

Hi I am getting the error The entity type List`1 is not part of the model for the current context at the following line of code
if (bureauEntities.Entry(subscription).State == EntityState.Detached)
public ActionResult UnSubscribe(int subscriptionTypeId, int companyId)
{
if (ModelState.IsValid)
{
using (BUREAUEntities bureauEntities = new BUREAUEntities())
{
var subscription = new SubcriptionRepository()
.AllIncluding(x => x.Exchanges, x => x.Users)
.ToList<Avanade.Bureau.DataAccessLayer.DatabaseModel.Subscription>().ToList<Avanade.Bureau.DataAccessLayer.DatabaseModel.Subscription>()
.Where(x => x.SubscriptionTypeId == subscriptionTypeId && x.CompanyId == companyId)// put where clasue here
.ToList<Avanade.Bureau.DataAccessLayer.DatabaseModel.Subscription>();
if (bureauEntities.Entry(subscription).State == EntityState.Detached)
{
// bureauEntities.Subscriptions.Attach(subscription);
}
//bureauEntities.Subscriptions.Remove(subscription);
bureauEntities.SaveChanges();
}
}
Could some one tell me what is the problem with the code?
DbContext.Entry(object) expects a single object. You are passing it a List<>. If you are expecting the the LINQ method to return only one value, append `.FirstOrDefault() to the query

Breeze throws Null reference exception when calling EntityAspect.validateProperty() method

I have the following entity property defined as the following metadata shows:
{"name":"website","dataType":"String",
"validators":[
{"name":"string"},
{"messageTemplate":"'%displayName%' is not valid",
"pattern":"^$|(^http|^https)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/S*)?",
"name":"regExValidator"}]}
When I attempt to call entityAspect.validateProperty("website"), and the value of the website property is null, the call to the validateProperty() method throws the following exception:
"Unable to get property 'complexAspect' of undefined or null
reference"
I wouldn't expect this behavior since it's possible that the website entity property could be null. It looks like there may be a null reference handling bug in the validateProperty method:
In Breeze.debug.js:
proto.validateProperty = function (property, context) {
var value = this.getPropertyValue(property); // performs validations
if (value.complexAspect) { // THROWS EXCEPTION IF 'value' IS NULL
return validateTarget(value);
}
context = context || {};
context.entity = this.entity;
if (typeof(property) === 'string') {
context.property = this.entity.entityType.getProperty(property, true);
context.propertyName = property;
} else {
context.property = property;
context.propertyName = property.name;
}
return this._validateProperty(value, context);
};
Just curious if I'm doing something wrong, or if this is just a bug?
Thanks,
Richard
Edit: This was fixed in Breeze v1.3.0, available now.
This is a bug, and will be fixed in the next release, out later this week. ... and thx for finding and reporting it :)

Resources