简体   繁体   中英

Linq with Dynamics CRM, how to handle null ? Object reference not set to an instance of an object

the join query given below gives error

(Object reference not set to an instance of an object)

it happen when there is no record returned by join:

 Contact party =
                   (from c in crmContext.pp_configurationSet
                    join p in crmContext.ContactSet
                    on c.pp_name equals p.FullName
                    where c.pp_name == "DeletedBy" &&
                    c.StateCode == pp_configurationState.Active
                    select p).FirstOrDefault().ToEntity<Contact>();

I just have check if I do not use . FirstOrDefault and ToEntity it do not throws error.

I need to return " Contact " from query. Can someone guide me on how to handle null check?

On Linq query, if you used FirstOrDefault which rturns the first element of a sequence, or a default value (The default value for reference and nullable types is null) if the sequence contains no elements. You can read about it here .

Over the result of FirstOrDefault you are invoking ToEntity method. If the result is null, the application will throw NullReferenceException (Object reference not set to an instance of an object). This is an expected flow.

Now to handle Null Check, either you can update ToEntity method if it's owned by you (it's not a linq method from System.Linq namespace) or write a new extension which should handle null and convert to ToEntity if result is not null.

FirstOrDefault returns null if there is no records found. This is what is causing the NullReferenceException on the ToEntity call.

You could expand this to two lines so you can do a null check, like so:

var party = (from c in crmContext.pp_configurationSet
                join p in crmContext.ContactSet
                on c.pp_name equals p.FullName
                where c.pp_name == "DeletedBy" &&
                c.StateCode == pp_configurationState.Active
                select p).FirstOrDefault();
if (party != null)
{
    Contact contact = party.ToEntity<Contact>();
}

Alternatively, you could use a null-conditional and null-coalescing operator for extra C# points:

Contact party = (from c in crmContext.pp_configurationSet
                join p in crmContext.ContactSet
                on c.pp_name equals p.FullName
                where c.pp_name == "DeletedBy" &&
                c.StateCode == pp_configurationState.Active
                select p).FirstOrDefault()?.ToEntity<Contact>() ?? new Contact();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM