0

I have a some field of entity

public virtual Trailer TempTrailer { get; set; }

How to change this fields value to null? I used:

var temptrailer = model.TempTrailer != null ? 
    await trailerService.FindByIdAsync(model.TempTrailer.Id) : 
    null;

entity.TempTrailer = temptrailer == null ? null : temptrailer;`

but does not accept null values. How to resolve this problem?

5
  • 2
    Is Trailer a struct or a class? Commented Dec 21, 2017 at 10:06
  • 1
    I assume that Trailer is a struct? Structs can't be null. So if you need to assign a null value, change the type from struct to class or change the declared type from Trailer to Trailer? or Nullable<Trailer> Commented Dec 21, 2017 at 10:08
  • Trailer is a class Commented Dec 21, 2017 at 10:13
  • What error are you getting? Commented Dec 21, 2017 at 10:14
  • Not have error,code working is good,but value is not changed Commented Dec 21, 2017 at 10:27

1 Answer 1

1

entity.TempTrailer = temptrailer == null ? null : temptrailer;

So basically, you are want to assign null, if temptrailer is null, otherwise temptrailer. You could also just write the following statement to achieve just the same:

entity.TempTrailer = temptrailer;

Nevertheless, if you want to assign a value using the conditional operator (?:), you can "cast" null:

entity.TempTrailer = temptrailer == null ? (Trailer)null : temptrailer;
Sign up to request clarification or add additional context in comments.

5 Comments

Your code is not working. In debug is work, in realese is not work I don't know why
Are you saying that after that statement, entity.TempTrailer is not null, or are you saying that the corresponding column in the corresponding row in the database is not null? Please be explicit about what the problem is instead of just "isn't working".
Me need change value of TempTrailer in DB. For example, Tractor have TempTrailer, In DB,in table Tractor have TempTrailer_ID Me need clear this TempTrailer_Id,that is clear this value
Are you working with Entity Framework? Are you saving your context?
Yeap,working with EF. Save with await Context.SaveChangesAsync();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.