Handle null values in MVC5 - c#

i have 50 properties in model name 'student' and im trying to set all properties NULL values to "" to prevent error messages in case of NULL.is there c# method that can do that?
thank you for your help.

You could initialize each property in your model (pretty simple with search/replace):
public string PropertyName { get; set; } = "";
However, I would question whether it is better to handle your NULL scenarios. It is pretty simple (model.PropertyName?.Method()).

Use a backing field for each.
In the get for each property, coalesce via return this.field ?? string.Empty;

Change the model to have fail safe check, as below.Will below work for you?
public class Student
{
private string _Name;
public string Name
{
get => string.IsNullOrWhiteSpace(_Name) ? string.Empty : _Name;
set => _Name = value;
}
//todo: rest of properties
}

Related

A good practice for setting computed properties

I am wondering what is a "good practice" for setting properties that are not mapped in the database. I am working with EF Core, but this is really more of a question of design. Imagine I have a following class:
class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string Name { get; set; }
...
}
Where Name would be computed after fetching the the FirstName and LastName from the database. I am trying to prevent calling the getter for Name without setting the property first.
I know I could do something like
class User
{
...
private string _name = null;
[NotMapped]
public string Name {
get
{
if (_name == null)
_name = $"{FirstName} {LastName}";
return _name;
}
}
...
}
But this gets really messy when multiple properties need to be set this way and when they are obtained in a more complicated way than this one-liner.
For now I wrote a function SetAllProperties() which sets all NotMapped properties, however I don't consider it a good solution since there is a risk of forgetting
To update it when new NotMapped properties are added
To actually call it before accessing the properties
Is an interface a way to go? How should it look like? Or is there some "standard" way of dealing with this? I wasn't able to find anything useful on this topic.

Update method in web API: How to know which fields to update?

I have a typical web API with a couple of PUT/UPDATE endpoints. These endpoints simply call the underlying service, and do the update.
The service layer, has the typical signature such as Object Update(Object object). What I then do is I basically run the following pseudo code:
var dbobject = _db.Object.Find(object.Id);
dbobject.Field1 = object.Field1;
dbobject.Field2 = object.Field2;
// continue for all fields
_db.SaveChanges();
return GetObjectById(object.Id);
However, this provides a challenge for me.
Lets say we have a consumer of our API. This consumer calls my PUT endpoint (/api/Object/{id}), and the payload is the updated Object.
However, lets say that the object we put don't know about example Field4, then this value would be NULL after the update has been run.
My question is:
What do you do about all those fields the payload does NOT contain?
How do you handle not setting values to NULL you don't expect to be
NULL afterwards?
As one of the possible ways, here can be used mix of NotifyPropertyChanged with automapper
The Idea is to store in DTO object which fields exactly was set, and which stays filled with default value. And use collected data in mapping.
For example DTO object will be
public class Dto
{
private List<string> Changed = new List<string>();
public bool IsChanged(string field) => Changed.Contains(field);
private int _age;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
// IMPORTANT: field name should fit main object field name
Changed.Add("Name");
}
}
public int Age
{
get { return _age; }
set
{
_age = value;
Changed.Add("Age");
}
}
}
I used Next class for test
public class Human
{
public string Name { get; set; } = "DEFAULT";
public int Age { get; set; } = -1;
}
and automapper configuration will looks like
cfg.CreateMap<Dto, Human>()
.ForAllMembers(s=> s.Condition(d=>d.IsChanged(s.DestinationMember.Name)));
This is a simple example. But it still doesn't prevent to use function IsChanged for some complex/specific logic, use not just a strings but Expressions / MethodInfo, or add custom attributes and use them in automapper configuration (DestinationMember is MethodInfo)
Append
Instead of complex DTO object the information about passed field you can get from Request.Properties in your controller (key ms_querynamevaluepairs value of type Dictionary<string, string>).

Projecting an entity to an anonymous object while some of its navigation properties might be null

I hope the question isn't confusing, what I'm trying to do is binding a list of anonymous object to a grid, I have a class Client, I am project a client into a list of anonymous object so that I can show its details in the grid, like this:
this.gridControl1.DataSource = _clients.Select(c => new
{
c.ClientId,
c.FirstName,
c.LastName,
c.Details.Country, //throws NullReferenceException since I added a
//client with no details.
c.Details.City,
c.Details.Adress,
c.Details.Email
}).OrderByDescending(c => c.ClientId);
Problem is some clients might not have details added yet..when trying to bind I get a NullReferenceException obviously..
The reason I'm doing a projection is to avoid having a column Details in the grid which is useless.
So, any solution? or a different approach to encounter this ? Thanks
Assuming that fields are strings, try
country = c.Details != null ? c.Details.Country : "", // or null or another
// appropriate default value
etc. instead of
c.Details.Country
You can use the ternary operator to do this:
c.Details == null ? null : c.Details.Country
Without seeing how Client is created I can't be sure what would work for you. Here are some suggestions:
Instantiate Client with a "blank" Details object which has string.Empty in all properties.
Make Client.Details a private property, then expose public properties (Country, City, etc) which have only getters and which return empty strings when the private Details object is null. If you need to access the Details object externally use a method instead of a property:
class Details
{
public string Country { get; set; }
}
class Client
{
private Details _details;
public string Country
{
get
{
return _details == null ? string.Empty : _details.Country;
}
}
public Details GetDetails()
{
return _details;
}
}
This would have the added benefit of allowing you to eliminate the anonymous selection, since the Details object would no longer be a Property and therefore ignored by the binding process. You could bind your clients collection directly to the grid.

ASP.Net MVC 3..0 Razor Property value?

can i set value for a property like this
public string MyProperty { get { return _GetValue(); } set { _GetValue(); } }
public static string _GetValue()
{
string name = null;
using (HROEF.Entities context = new HROEF.Entities())
{
var result = (from my linq Statement).First().ToString();
name = result;
}
return name;
}
In my View
#Html.DisplayFor(model=>Model.MyProperty)
is there any thing wrong in this?
It is not displaying the value in my view
any help?
In general, you shouldn't be doing database accessin properties. It's just bad practice. Properties should not perform lengthy operations that can time out, or have other issues.
As for why it's not showing your value, that's hard to say. Most likely, your linq query simply isn't returning any results.

DataAnnotations WriteOnly if property == null

I have the following property:
public virtual String Firstname { get; set; }
and i only want to be able to write to the field IF it is currently null (not set), it this possible to achieve through DataAnnotations?
Data annotations are metadata used for example for validation so you can create custom data annotation to validate property value but the validation cannot ensure that your property will not be set if it already has value. That is code which should be part of property's setter itself like:
private string _firstName;
public string FirstName
{
get
{
return _firstName;
}
set
{
if (_firstName != null) throw ...
_firstName = value;
}
}
If by data annotations you simply mean attributes then the answer is: It can be achieved with attributes BUT you need something which will implement some logic related to the attribute. This is usually done through Aspect oriented programming (AOP) where you will create marker attribute which will be used by some complex API. The API will based on that attribute wrap your class with custom code adding the if statement either at compile time (for example PostSharp) or at runtime (for example Unity, Spring.NET).
Another way to achive this, by me more elegant, do not implement set for the property, but only get
private string _firstName;
public string FirstName
{
get
{
return _firstName;
}
}
and have a function:
public void SetFirstName(string FirstName)
{
_firstName = FirstName;
}
So no exception, no return value handling. You have one property the only retrieve value, and one function, or constructor (why not, depends on your architecture, it's hard to deduct from post) that initialized it only once.
By me the API of your object will be more clear and straightforward in this way.
Regards.
There is also a specific DataAnnotation syntax to achieve this:
[DisplayFormat(NullDisplayText = "some string")]
public virtual String Firstname { get; set; }

Categories

Resources