copying one objects data to other? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to update EF record, in method I have EF object and another new objct which I want to use to update data from. But I m not sure how to copy data from new object to existing one.
Help please.
Here is my code:
public int PostHomeLead(string _lead)
{
try
{
int result = 0;
Lead lead = new Lead();
lead = new JavaScriptSerializer().Deserialize<Lead>(_lead);
//check if lead exist with same session id, if so update it other wise add new.
Lead existingLead = new Lead();
existingLead = db2.HomeLoanCustRepo.GetByID(lead.Lead_id);
if (existingLead == null)
{
db2.HomeLoanCustRepo.Insert(lead);
db2.Save();
result = 1;
}
else
{
db2.HomeLoanCustRepo.Update(lead);
db2.Save();
result = 1;
}
return result;
}
catch(Exception ex)
{
throw ex;
}
}

Either map the properties manually:
existingLead.Foo = deserializedLead.Foo;
existingLead.Bar = deserializedLead.Bar;
existingLead.Baz = deserializedLead.Baz;
Or use a library that does this, like AutoMapper.
As for your comment, creating a deep copy is what you seem to be after. Note this allows for overposting or mass assignment when you don't verify which properties may be updated. You'll need to Attach() the cloned object when using cloning or mapping, as it will not be the same object as returned by GetByID(), so Entity Framework's change tracker won't recognize it.

Related

Should I assign object properties when initializing or after initializing? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have an object obj1 with 11 properties.
Is it better to do this
Obj obj1 = new Obj()
{
prop1 = int.Parse(data.Rows[0]["RequestId"].ToString())
prop2 = IsBoss = (bool)data.Rows[0]["IsBoss"]
///etc...
}
or should I do
{
Obj obj1 = new Obj(){}
obj1.prop1 = int.Parse(data.Rows[0]["RequestId"].ToString())
obj1.prop2 = IsBoss = (bool)data.Rows[0]["IsBoss"]
///etc...
}
Also as a side question, when my data rows are null, an exception "Input string was not in a correct format" gets thrown because the field from the database is null. Typically the data wouldnt be null but would it be best to use a ternary operator to check if null or should i do a case in the sql qry.
Like the other answers, how you instantiate an object is up to you. Personally, I used to instantiate them and assign the properties all in one statement. The issue that I kept running into is when a had a property that failed to make it back from the database (like your null exception scenario), the the exception wouldn't give me an accurate line number. For that reason, I've moved to instantiating the object, then assigning the properties. This way, you'll know exactly which line/property is causing the issue.
MyClass obj = new MyClass();
obj.PropertyOne = "";
obj.PropertyTwo = "";
//etc...
As far as your second question goes, I handle nulls by using a ternary in combination with the IsDBNull() method on the DataTableReader.
MyClass obj = new MyClass();
obj.PropertyOne = rdr.IsDBNull(rdr.GetOrdinal("RequestId")) ? 0
: rdr.GetInt32(rdr.GetOrdinal("RequestId"));
I prefer setting object properties on initialization as per the first example, I think the code looks cleaner and better contained, but that is more of a personal preference.
For your second question when data is null coming back from the database you've got a few options.
{
var obj1 = new Obj()
{
prop1 = int.TryParse(data.Rows[0]["RequestId"]?.ToString(), out int val) ? val : -1,
prop2 = IsBoss = bool.TryParse(data.Rows[0]["IsBoss"].ToString(), out bool isBoss) ? isBoss : false
}
}
Haven't tested but something like that should work, but it's not clean. I'd separate out the parsing into its own method or block. To help the code breathe a little.
Something like this:
{
if(!(int.TryParse(data.Rows[0]["RequestId"]?.ToString(), out int requestId)))
{
requestId = -1;
}
bool.TryParse(data.Rows[0]["IsBoss"]?.ToString(), out IsBoss);
var obj1 = new Obj()
{
prop1 = requestId,
prop2 = IsBoss
}
}

SessionBag missing in servicestack version 4.5.0 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to servicestack and using servicestack version 4.5.0.
With reference to the ServiceStack 'session' missing?
Where can I find this base.SessionBag property ? with base keyword I am getting
these intellisense
please help me.
what does this line means:
Inside a Service the dynamic untyped Session Bag was renamed to base.SessionBag.
what does this line means:
Inside a Service the dynamic untyped Session Bag was renamed to base.SessionBag.
when I write base. I find following intellisense
base.Session //-- Property Method
base.SaveSession //--- Extension
base.SessionAs<>
base.SessionFactory //-- Property Method
public class EntryService : Service
{
public object Post(Entry request)
{
var date = request.Time.Date;
var trackedData = (TrackedData)Session= date.ToString();
if(trackedData == null)
trackedData = new TrackedData { Goal = 300 };
trackedData.Total += request.Amount;
Session[date.ToString()] = trackedData;
return new EntryResponse { Id = 1};
}
}
i want like this
Session[date.ToString()] = trackedData;
but an error occurs Cannot apply indexing with [] to an expression of type ServiceStack.CacheAccess.ISession
You have to inherit from ServiceStack's Service base class. You can then access the dynamic Session Bag with base.SessionBag.

What are C# chaining functional approach caveats? What to do with "ifs"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Recently I watched Pluralsight course "Functional programming in C#". And rewrote some methods in my hobby project. Now they look like this:
public override CommandLineResult GetResult()
{
return Disposable.Using(new IndicatorRepository(), repo =>
{
return repo.AddOrUpdateIndicator(Indicator, Value, DateTimeExtensions.LocalNow().Date);
})
.Map((p) => new NumericIndicatorRecorderedModel()
{
Id = Guid.NewGuid().ToString(),
DbActionPreformed = true,
IsRewritten = Convert.ToBoolean(p),
IndicatorName = Indicator,
Value = Value,
ValueDate = ValueDate
})
.Map((model) => new CommandLineResult()
{
ActionName = "~/Views/CommandLine/_clresult_NumericIndicatorRecorderedModel.cshtml",
Model = model
});
}
There's something pretty about this chaining approach (I removed Using with Disposable class, at every step I have expressions, not statements, etc.).
But the questions are:
Does not this approach covers some dangers? and what are they? (isn't it more difficult to debug for example)
What usually people do in terms of chaining approach, if it is required to branch the flow of code execution? Break chain with ifs somewhere? Write "map-if" functional extensions (would not that approach create spaghetti code?)?
UPDATE: more specific question regarding this issue
What approach to implement code branching is better - to break chaining like this:
public string GetResult(bool param) {
if (param) {
return MyClass.DoOneWay(p =>...).AlsoDo(q =>...).ToString();
}
else
{
return MyClass.DoOtherWay(p =>...).AlsoDo(q =>...).ToString();
}
}
Or to implement functional if-helpers, like this:
public string GetResult(bool param)
{
return MyClass.DoIf(param, p => ...., q => ....).AlsoDo(q =>...).ToString();
}
And what to do, if there're much more options then just true/false?
How to "functionaly" implement "switch" branching?

Entity Framework create update query unnecessary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to update record with LINQ to SQL but in some case value is same as original value then also Enitty framework create Update query unnecessary.
var objForupdate = context.temp.FirstOrDefault();
if(objForupdate != null)
{
objForupdate.Name = "VJ"; // Original Value also "VJ"
}
// Create update query for above.
context.SaveChanges();
Updated
Hey Steven Wood
Here I have scenario where my DB has 20 fields. Sometime some data is same as original data then also Entity framework create update query for that.
It is simple if data row is not in dirty state then no need to update it. But entity frame work create Update query for that also. Just use profile tool to check what kind of query executed on DB server after SaveChanges() method executed.
Solutions
Use following function to check entity object changed or not. If not then it will change it to EntityState.Unchanged from EntityState.Modified.
public static bool ChangeStateIfNotModified(this EntityObject entity, ObjectContext context)
{
if (entity.EntityState == EntityState.Modified)
{
ObjectStateEntry state = ontext.ObjectStateManager.GetObjectStateEntry(entity);
DbDataRecord orig = state.OriginalValues;
CurrentValueRecord curr = state.CurrentValues;
bool changed = false;
for (int i = 0; i < orig.FieldCount; ++i)
{
object origValue = orig.GetValue(i);
object curValue = curr.GetValue(i);
if (!origValue.Equals(curValue) && (!(origValue is byte[]) || !((byte[])origValue).SequenceEqual((byte[])curValue)))
{
changed = true;
break;
}
}
if (!changed)
{
state.ChangeState(EntityState.Unchanged);
}
return !changed;
}
return false;
}
If you're looking to not execute the update if the two values are the same, why not do something like:
if(objForUpdate.Name != orignalValue){
context.SaveChanges();
}
Make sure you dispose your context where appropriate. For instance, if this is in a MVC controller, I'd dispose your context in the controller's Dispose() method.
You should use String.Empty instead of '' and verify that the value is really the same or not while debugging.
EDIT: Are you sure it's exactly the same value?
If I take a look at the generated code for a property, it looks like this:
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String id
{
get
{
return _id;
}
set
{
if (_id != value)
{
OnidChanging(value);
ReportPropertyChanging("id");
_id = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("id");
OnidChanged();
}
}
}
private global::System.String _id;
So the value are being compared. Verify the code generated and set a breakpoint to debug it. If the state is changed, then a query would occur. If it's not entering inside the if condition and the update query still occur, the problem is elsewhere.

C# get name of object as string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an object named 'Account' and the following code:
Account objAcc = new Account();
objAcc.Name = "Test";
The above is working fine, as expected. I now have a list of values as follows:
string props = "Name,Address,Telephone";
Now, what I want to do is see if "Name" exists in that list. I only have the object to use though (hard coding a case statement etc isn't possible as the object is dynamic), so from objAcc.Name, I somehow need to get "Name" from that, and then see if it's in the list.
Thanks in advance, I hope it's clear enough,
Dave
You can use reflection, by doing that :
var properties = objAcc.GetType().GetProperties();
foreach(var property in properties)
{
if(props.Contains(property.Name))
{
//Do you stuff
}
}
string test = objAcc.GetType().GetProperty("Name") == null ? "" : objAcc.GetType().GetProperty("Name").Name;
bool result = "Name,Address,Telephone".Split(',').Contains(test);
You may use the following method if you like:
public bool PropertyExists<T>(string propertyName, IEnumerable<string> propertyList,T obj)
{
string test = obj.GetType().GetProperty(propertyName) == null ? "" : obj.GetType().GetProperty(propertyName).Name;
bool result = propertyList.Contains(test);
return result;
}
Giannis

Categories

Resources