views:

43

answers:

1

How to: you don't want to manually write code to write to ColumnA, ColumnB, etc, then you could use reflection to write to the appropriate properties on the entity? you can create a new instance of this class and its property values. These property values are mapped to columns in the SQL database table. You then pass this object to the DataContext class generated by LINQ to SQL, to add a new row to the table in the database.

So, you would do something like this:


For a database table with columns "ColumnA", "ColumnB" and "ColumnC"

var myEntity = new EntityObject { ColumnA = "valueA", ColumnB = "valueB", "ColumnC" = "valueC" };
DataContext.InsertOnSubmit(myEntity);
DataContext.SubmitChanges();

This will insert a new row into the database with the column values specified.

Now if you don't want to manually write code to write to ColumnA, ColumnB, etc, then you could use reflection to write to the appropriate properties on the entity:

For example, with entity instance 'myEntity':


var properties = myEntity.GetType().GetProperties();

foreach (string ky in ld.Keys)
{
    var matchingProperty = properties.Where(p => p.Name.Equals(ky)).FirstOrDefault();
    if (matchingProperty != null)
    {
        matchingProperty.SetValue(myEntity, ld[ky], null);
    }
}

i try to this but i cannot. How can you make it?

A: 

Check this article : LINQ to SQL: All common operations (Insert, Update, Delete, Get) in one base class Following might help you :

protected virtual void Update(T entity, Expression<Func<T, bool>> query)
{
   using (DC db = new DC())
   {
    object propertyValue = null;
        T entityFromDB = db.GetTable<T>().Where(query).SingleOrDefault();
          if (null == entityFromDB)
             throw new NullReferenceException("Query Supplied to " + 
                   "Get entity from DB is invalid, NULL value returned");
        PropertyInfo[] properties = entityFromDB.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
           propertyValue = null;
                if (null != property.GetSetMethod())
                {
                  PropertyInfo entityProperty = 
                        entity.GetType().GetProperty(property.Name);
                    if (entityProperty.PropertyType.BaseType == 
                        Type.GetType("System.ValueType")|| 
                        entityProperty.PropertyType == 
                        Type.GetType("System.String"))

                      propertyValue = 
                       entity.GetType().GetProperty(property.Name).GetValue(entity, null);
                    if (null != propertyValue)
                        property.SetValue(entityFromDB, propertyValue, null);
                }
            }
            db.SubmitChanges();
        }
    }
Pranay Rana