• notice
  • Congratulations on the launch of the Sought Tech site

C# insert or update null value into database and lazy loading lazy

Insert or update null value

1. Insert null or empty string "" directly in SQL statement

int? item = null; item == null ? "null" 
 : item.ToString(); item == null ? "" : item.ToString();

2. Using the command parameter, insert DBNull.Value

int? item = null; cmd.Parameters.Add(dbPams.MakeInParam(":Item", SqlNull(item))); cmd.Parameters[0].IsNullable = true;//This sentence needs to be added when updating. static public object SqlNull(object obj) { 
    return (item == null ? DBNull.Value : item) }

lazy loading

. In. NET4.0, you can use Lazy to achieve lazy initialization of objects, thereby optimizing the performance of the system.

As we know, the loading of objects takes time, especially for large objects. Lazy can achieve lazy loading of objects. Lazy loading means that objects are created when they are used rather than when they are instantiated.

Lazy object initialization is thread-safe by default. In a multi-threaded environment, the first thread that accesses the Value property of the Lazy object will initialize the Lazy object, and subsequent threads will use the data initialized for the first time.

1. Scenarios for the main application of delayed loading:

  • Data layer (ORM such as ADO.NET or Entity Framework, Hibernate in Java also uses this technology)

  • Reflection (load assembly, type, MEF)

  • cache objects, domain entities

  • singleton pattern

2. Simple usage

As follows: The IsValueCreated attribute shows whether it has been created.

static void Main(string[] args) { 
 Lazy lazyBig = new Lazy(); 
 Console.WriteLine("Whether the object is created" + lazyBig.IsValueCreated); 
 lazyBig.Value.Test(); 
 Console.WriteLine("Whether the object is created" + lazyBig.IsValueCreated); } class Big { 
 public Big() { } 
 public void Test() { 
   Console.WriteLine("Test...."); } 
 } //The result is as follows: //Whether the object is created False // Test.... //Whether the object is created True

It can be seen that the object created according to lazy will only be initialized when it is used for the first time.

Alternatively, lazy can be created using delegates.

static void Main(string[] args) { 
    Lazy lazyBig = new Lazy( () => new Big(100) ); 
    lazyBig.Value.Test(); } class Big { 
  public Big(int id) { this.ID = id; } 
  public int ID { get; set; } 
  public void Test() 
    { 
        Console.WriteLine("ID = " + ID.ToString()); 
    } }


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+