1

I want to insert blank space or some default value if string is null or empty for all tables before insert (because Oracle considers blank value as null, but it's working fine with SQL Server). I am using Entity Framework 6.0.

After googling a lot, I found a similar answer here. But this does not work for me. It is showing an error

object does not contain definition for Value

How can I achieve this using Entity Framework interceptor?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
deepak neo
  • 61
  • 1
  • 8
  • In the Setter of the Propriety check if the value is null then but what ever you want or you can give it a default value – IbraHim M. Nada Dec 12 '17 at 10:53
  • Use the code from the link, but replace `foreach (var p in command.Parameters)` with `foreach (var p in command.Parameters.Cast())` – Ivan Stoev Dec 12 '17 at 11:05
  • @IvanStoev your code showing error - System.Data.Common.DbParameterCollection' does not contain a definition for 'Cast' and no extension method 'Cast' accepting a first argument of type 'System.Data.Common.DbParameterCollection' could be found (are you missing a using directive or an assembly reference?) – deepak neo Dec 12 '17 at 11:12
  • @deepakneo You know how to resolve such errors, don't you? Control+Dot, light bulb etc to add `using System.Linq;` Or just the old stype casting foreach which I was trying to avoid `foreach (DbParameter p in command.Parameters)` – Ivan Stoev Dec 12 '17 at 11:18
  • @IvanStoev i tried ctr+space and ctr+. but it did not worked. adding System.Linq manually worked for me. btw thanks will check and reply if it does my work – deepak neo Dec 12 '17 at 11:25
  • @IvanStoev post your answer i will mark it as answer – deepak neo Dec 12 '17 at 11:30
  • 1
    Thanks mate, glad it helped. But this was a problem and hence should have been fixed in the highly upvoted answer from the link. I think it would be more appropriate if you post self answer how did you resolve the issue in question. – Ivan Stoev Dec 12 '17 at 11:34

2 Answers2

1
 public class StringInterceptor : IDbCommandInterceptor
    {
        public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            foreach (var p in command.Parameters.Cast<DbParameter>())
            {
                if (p.Value is string)
                {
                    if (((string)p.Value) == string.Empty)
                    {
                        p.Value = " ";
                    }
                }

            }

        }

Finally i solved this. thanks to @Ivan Stoev

deepak neo
  • 61
  • 1
  • 8
0

You have to override SaveChange(). This link will give you an idea - Overriding SaveChanges and setting ModifiedDate, but how do I set ModifiedBy?

Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28
  • how can i use this solution to replace my all null string with blank space ? i dont know field name it can be anything – deepak neo Dec 12 '17 at 11:15