C# Mapping struct in ActiveRecord - c#

i am making a little application to help me balance my checkbook.
i am using Castle ActiveRecord to map the object properties to the database. now here is the problem. as i am making a money program i made a struct Currency
The struct:
public struct Currency
{
private long amount;
private CurrencyType currencyType;
public long Amount
{
get { return this.amount; }
set { this.amount = value; }
}
public CurrencyType CurrencyType
{
get { return this.currencyType; }
set { this.currencyType = value; }
}
}
The class i am mapping:
[ActiveRecord("[Transaction]")]
public class Transaction: HasOwnerModelBase
{
private Currency amount;
private Category category;
[BelongsTo]
public virtual Category Category
{
get { return this.category; }
set { this.category = value; }
}
public virtual Currency Amount
{
get { return this.amount; }
set { this.amount = value; }
}
}
Now in the ideal situation the Currency object would act like a nested object so the amount and currencyType are two colums in the transaction table.
but it is not a nested seeing as i want it to act like the currency struct object.
I have no idea what tag i should give the Currency Amount for it to work, i would really appreciate it if any one could help me solve this problem.
I hope all of this is clear.
Greatings Duncan

What about the following? Or didn't I get the question? Note that I changed the structure to a class because you need virtual members for dynamic proxy generation and you cannot have virtual members on structures. By the way, why don't you use auto-implemented properties?
public class Currency
{
[Property]
public virtual Int64 Amount { get; set; }
[Property]
public virtual CurrencyType CurrencyType { get; set; }
}
[ActiveRecord("[Transaction]")]
public class Transaction: HasOwnerModelBase
{
[BelongsTo]
public virtual Category Category { get; set; }
[Nested]
public virtual Currency Amount { get; set; }
}

Related

Common action executed for multiple getters

I'm trying to find a neat way to trigger a loading mechanism when one of several getters is first accessed. My first thoughts are about something like this:
public class Customer {
private bool loaded = false;
public int PK { get; set; }
public string Email { get; set; }
public string Name { get { if (!loaded) loadData(); return _name; } set { ... } }
public string Street { get { if (!loaded) loadData(); return _street; } set { ... } }
public string City { get { if (!loaded) loadData(); return _city; } set { ... } }
}
In short, in this example every Customer exists with its base data PK and Email until one of the other properties is accessed.
This would mean much duplicate code, increasing with the complexity of the class. Is there a way to create some kind of inheritance for these properties?
Something like this, but I don't think this is possible:
private void checkData() { if (!loaded) loadData(); }
public string Name:checkData { get; set; }
public string Street:checkData { get; set; }
public string City:checkData { get; set; }
Another way might be possible through reflection, but as I'm not experienced with it I don't know where to start here.
Any hints are deeply appreciated! ;-)
You can use the Lazy<T> class to wrap the secondary properties.
This way loadData will only execute if any of the secondary getters is called and won't be executed more than once.
public class Customer
{
public int PK { get; set; }
public string Email { get; set; }
public string Name { get { return data.Value.Name; } }
public string Street { get { return data.Value.Street; } }
public string City { get { return data.Value.City; } }
public Customer()
{
data = new Lazy<CustomerData>(loadData);
}
private CustomerData loadData()
{
...
}
private struct CustomerData
{
public string Name, Street, City;
}
private Lazy<CustomerData> data;
}
There is another, not so beautiful, way. You could write a wrapping generic method, which reduces the code inside your properties.
Here's an example:
public string Name
{
get { return Get(m_name); }
set { m_name = value; }
}
public static T Get<T>(T value)
{
if (!loaded)
{
loadData();
}
return value;
}
Please note, that this will decrease the performance, because your properties will always call an extra method. You can try to force the compiler to inline that method (if it does not happen already).

How to get difference properties of object in c#?

i have a class with some properties like this:
public class Car
{
public long No { get; set; }
public string Name { get; set; }
public int Door { get; set; }
public Color Color { get; set; }
public int MaxSpeed { get; set; }
public int Price { get; set; }
}
(this class is an example, my real class is very bigger than it.)
In my program, I need to get difference properties of this class from db(not all properties each time). For example in one case I need name and color of some cars, and in other case I need name and door and price.
I want to create one method that support all difference conditions. I know that i could create it using ‘params’ and ‘enum’, but I am research about best way to do it. Thanks
You can just query the propertie when it is called.
public int Value{
get{
int myValue = getValue();
return myValue;
}
}
Try do this way:
public object[] GetProperties(int state)
{
object[] temp;
switch(state)
{
case(0):
{
temp=new object[]{Name,Color};
}break;
case(1):
{
temp=new object[]{Name,door};
}
}
}
After that, you know , what need return your function, and it's easy parse return result!

Changing a model without altering the database?

I've got a model being used to populate a database
public class Account
{
public int NumberOfPayPeriods { get { return 24; } }
public decimal YearAmount { get; set; }
public decimal PlanTotal
{
get { return NumberOfPayPeriods*YearAmount; }
}
}
The NumberOfPayPeriods attribute I need to change from just a get to a get; set;
However, when I change this, I get an EntityCommandExecutionException (invalid column name). I assume this is because it is trying to map this to the database where there previously existed no such column (as it was only a get).
Is there any way I can change this to a get;set; without having to delete the table? There's a lot of important data on there that cannot be lost or re-created.
Add a [NotMapped] attribute over the property you don't want stored.
public class Account
{
[NotMapped]
public int NumberOfPayPeriods { get { return 24; } set { ... } }
public decimal YearAmount { get; set; }
public decimal PlanTotal
{
get { return NumberOfPayPeriods*YearAmount; }
}
}

How to make two similar functions into one function?

I have two functions that do the basically same thing on two different classes.... each class has different properties.
For example:
public class ClassA
{
public int ColorID {get;set;}
public string ColorDescription {get;set;}
}
public class ClassB
{
public int TypeID {get;set;}
public string TypeDescription {get;set;}
}
public void ExFunctionSaveA(ClassA aClass)
{
aClass.ColorID=1;
aClass.ColorDescription="My Color";
Save();
}
public void ExFunctionSaveB(ClassB bClass)
{
bClass.TypeID=2;
bClass.TypeDescription="My Type";
Save();
}
As you can see the classes and the functions have the same type structure, just the property names are different... but I feel like I am repeating code doing this
Is there a way to make ExFunctionA and ExFunctionB into one function, so that I could use this for all classes that have similar structure
I know I could do some sort of generic thing like
public void ExFunctionSave<T>() // T is either ClassA or ClassB
{
.
.
.
.
Save();
}
but how would I handle the properties of each
Rather than using a generic, why not use inheritance to solve this?
public class theBase
{
string ID;
string Description;
}
public class theColor : theBase
{
}
public class theType : theBase
{
}
public void ExFunctionSaveA(theBase base)
{
base.ID=1;
base.Description="My Color";
Save();
}
If you can alter the definitions of your classes, then the best approach would be to make them implement a common interface that contains the properties you want to access:
public interface IDescribable
{
int ID { get; set; }
string Description { get; set; }
}
public class ClassA
{
public int ID { get; set; }
public string Description { get; set; }
public int ColorID
{
get { return ID; }
set { ID = value; }
}
public string ColorDescription
{
get { return Description; }
set { Description = value; }
}
}
public class ClassB
{
public int ID { get; set; }
public string Description { get; set; }
public int TypeID
{
get { return ID; }
set { ID = value; }
}
public string TypeDescription
{
get { return Description; }
set { Description = value; }
}
}
public void ExFunctionSave(IDescribable d, int id, string desc)
{
d.ID = id;
d.Description = desc;
Save();
}
Nothing more you can do unless the the 2 classes implement the same interface which has the function. In your case, even the function signatures are different.
You could define an Interface with attributes id and description.
The clases that has this structure could implement that interface.
And your method receive as parameter the interface and execute the moethods ...
Take a look at Reflection.
Reflection will let your code receive a ClassA, and discover that it has a ColourID and a ColorDescription. Likewise, when you receive a ClassB, you can discover its TypeID and TypeDescription. It's cool.
I would probably recommend a common interface, at least for your example, but if you're trying to something more complex and more generic, Reflection is the way to go.

Why Does Lack of Cohesion Of Methods (LCOM) Include Getters and Setters

I am looking at the LCOM metric as shown here,
http://www.ndepend.com/Metrics.aspx
So we are saying a few things,
1) A class is utterly cohesive if all its methods use all its instance fields
2) Both static and instance methods are counted, it includes also constructors, properties getters/setters, events add/remove methods
If I look at a class such as this,
public class Assessment
{
public int StartMetres { get; set; }
public int EndMetres { get; set; }
public decimal? NumericResponse { get; set; }
public string FreeResponse { get; set; }
public string Responsetype { get; set; }
public string ItemResponseDescription { get; set; }
public string StartText { get; set; }
public decimal? SummaryWeight { get; set; }
}
It gets a bad score of 0.94 because each getter and setter doesn't access 'all of the other instance fields'.
It is calculated like this,
accessAverage - methodCount / 1 - methodCount
(2 - 17) / (1 - 17) = 0.94 (rounded)
I am not understanding this metric, why should it include getters and setters? A getter and setter will always only access one single instance field.
This demonstrates that every software metric is flawed if you blindly take it to its extreme.
You know an "incohesive" class when you see one. For example:
class HedgeHog_And_AfricanCountry
{
private HedgeHog _hedgeHog;
private Nation _africanNation;
public ulong NumberOfQuills { get { return _hedgeHog.NumberOfQuills; } }
public int CountOfAntsEatenToday { get { return _hedgeHog.AntsEatenToday.Count(); } }
public decimal GrossDomesticProduct { get { return _africanNation.GDP; } }
public ulong Population { get { return _africanNation.Population; } }
}
This is obviously an incohesive class, because it contains two pieces of data that don't need to be with one another.
But while it's obvious to us that this class is incohesive, how can you get a software program to determine incohesion? How would it tell that the above class is incohesive, but this isn't?
class Customer
{
public string FullName { get; set; }
public Address PostalAddress { get; set; }
}
The metric they came up with certainly detects incohesion, but also comes up with false positives.
What if you decided this metric was important? You could create a "CustomerData" class containing just fields, and a "Customer" class that exposes the data fields as properties.
// This has no methods or getters, so gets a good cohesion value.
class CustomerData
{
public string FullName;
public Address PostalAddress;
}
// All of the getters and methods are on the same object
class Customer
{
private CustomerData _customerData;
public string FullName { get { return _customerData.FullName; } }
// etc
}
But if I'm playing this game, I can apply it to the incohesive example as well:
class Hedgehog_And_AfricanCountry_Data
{
public Hedgehog _hedgehog;
public AfricanNation _africanNation;
}
class Hedgehog_And_AfricanCountry
{
private Hedgehog_And_AfricanCountry_Data _hedgehogAndAfricanCountryData;
// etc;
}
Really, I think it's best to understand what cohesion is, and why it's a worthwhile goal, but also understand that a software tool can not properly measure it.

Categories