Declaring class as properties inside another class [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 copied this code from this article and I don't get any idea why define class inside classes as properties. Also, what happens when the class PersonalLoan is instantiated ?
public class PersonalLoan
{
public string AccountNumber { get; set; }
public string AccounHolderName { get; set; }
public Loan LoanDetail { get; set; }
public PersonalLoan(string accountNumber)
{
this.AccountNumber = accountNumber;
this.AccounHolderName = "Sourav";
this.LoanDetail = new Loan(this.AccountNumber);
}
}
public class Loan
{
public string AccountNumber { get; set; }
public float LoanAmount { get; set; }
public bool IsLoanApproved { get; set; }
public Loan(string accountNumber)
{
Console.WriteLine("Loan loading started");
this.AccountNumber = accountNumber;
this.LoanAmount = 1000;
this.IsLoanApproved = true;
Console.WriteLine("Loan loading started");
}
}

I suspect that this code snippet is an example of what you should avoid: LoanDetail property of type Loan inside a class PersonalLoan suggests a has-a relationship between the classes. In other words, the authors of this code snippet are trying to say that
Personal loan has a Loan
This, however, is unlikely the relationship that they are trying to model: in reality,
Personal loan is a Loan
The relationship is-a is modeled using inheritance, not composition. In other words, they should have written this:
public class PersonalLoan : Loan {
public PersonalLoan(string accountNumber) : base(accountNumber) {
...
}
...
}
Another issue that points to the model being incorrect is that both PersonalLoan and the Loan inside it have the same accountNumber, which is stored in two places within the same object. When you see this, you know something is not right. The reason you get two account numbers is that when PersonalLoan gets instantiated, its constructor also instantiates Loan, passing it the same accountNumber.
This is not to say that embedding objects inside other objects is wrong. For example, if you were to model a borrower address as a class, you would end up with something like this:
class Address {
public string Country {get;set;}
public string City {get;set;}
... // And so on
}
class Borrower {
public Address MailingAddress {get;set;}
... //
}
This model is perfectly valid, because Borrower has an Address.

Related

Is it possible to remove property from Custom Class in c# [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 3 years ago.
Improve this question
public class abc
{
public int id{get;set;}
public string name{get;set;}
}
I want to remove property name from class abc dynamically. is it possible in c#?
No, after compilation the class definition can't be changed. What you can do is. Make a list of properties you want to Ignore.
or you can Create a custom attribute. Add it on the property then get the List of Properties excluding the ones with that Attribute
For example
public class abc
{
public int id{get;set;}
[IgnoredProperty]
public string name{get;set;}
}
Now In Loop For example you can do this.
foreach (var prop in typeof(abc).GetProperties().Where(x => !Attribute.IsDefined(x,typeof(IgnoredProperty))).ToList())
{
}
This can be the attribute Class
public class IgnoredPropertyAttribute : Attribute
{
}
Ignoring "dynamic" for the moment, here's what you could do with interfaces:
public interface IAbcId {
Id {get; set;}
}
public class Abc : IAbcId {
public Id {get; set;}
public Name {get; set;}
}
....
public class Consumer {
void CallingFunction()
{
var obj = new Abc();
// obj will have Name and Id properties visible here
ConsumingFunction(obj)
// or
IAbcId iAbc = new Abc();
//iAbc.Name will not be visible here
}
void ConsumingFunction ( IAbcId item )
{
// item will only have Id property visible.
}
}

Populating list property in ctor based on other property

My application is basically just a survey with questions and multiple choice answers. Questions have Answers, but a specific Answer may lead to a specific Question being asked which might otherwise not be asked at all. e.g. "Do you like chocolate?" (if yes ask...) "Do you prefer German or Dutch chocolate?"
In the Answer class, I am trying to populate a list property "DependentQuestions" which is meant to contain id numbers for the Quesiton(s) that will be asked next if this Answer is chosen. The problem is, I am always getting nothing and I'm not sure why. I confirmed the Answer.id is zero at the time the constructor runs by populating DependentQuestions with the commented code you'll see below.
Each Question has an icollection of Answers.
Question class:
public class Question
{
[Key]
public int id { get; set; }
public string question { get; set; }
public int? DependentAnswer { get; set; }
public virtual ICollection<Answer> answers { get; set; }
}
Answer class:
public class Answer
{
[Key]
public int id { get; set; }
public string answer { get; set; }
[Required]
public int questionId { get; set; }
public List<int> DependentQuestions { get; set; }
public Answer()
{
DependentQuestions = new List<int>();
using (dbSurvey db = new dbSurvey())
{
var _list = db.Questions.Where(q => q.DependentAnswer == id).Select(q => q.id).ToList();
if (_list.Any())
{
DependentQuestions.AddRange(_list);
}
//else
//{
// DependentQuestions.Add(id);
//}
}
}
}
The "answers" collection of the Question class is being filled with the Answers to the given Question and that works just fine, but the DependentQuestions list in the Answer class is always coming up empty since Answer.id is always zero at that point. So why is Answer.id always 0, and what can I do about it?
Constructor code is run before any property values are set, so at the point of executing the constructor all properties just contain their default values. That is why it is always 0.
I am not sure what are you using as a data access framework, but generally you can do few things:
Create Answer entity with id, so you always have it in constructor:
public Answer(int id)
If that's not an option, you could also have a lazy property loading questions as needed:
class Answer
{
private List<int> _dependentQuestions;
public List<int> DependentQuestions
{
get
{
if (_dependentQuestions == null)
// load questions here
return _dependentQuestions;
}
}
}
Note that this assumes id is already set, you probably should validate that too.

How to use a class created by the entity framework [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 6 years ago.
Improve this question
I have a project coming up so I decided to look at the entity framework. If I don't have to create a data manager I think this would be the way to go, if it works. I see lots of things about it but none of them are clear.
It created this class
namespace EFTest
{
using System;
using System.Collections.Generic;
public partial class SalesRepresentative
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}
How do I use it? Looking for examples I see things like this:
using (var ctx = new Context())
{
Employee emp = new Employee() { name = "Prashant" };
ctx.Employees.Add(emp);
ctx.SaveChanges();
}
I have a file called Model.Comntext with no context class in it. I tried changing it to dBContext but that doesn't work either.
I also found this:
CustomersComponent custc = new CustomersComponent();
Customers cust = custc.getCustomer(Id);
txtName.Text = cust.Name;
ddlCategories.SelectedValue = cust.Category.Id.ToString();
Well that has a Customer and a CustomerComponent. I have no such Component classes. I've spent half a day looking into this and am starting to wonder if the Entity Framework is a cousin of Microsoft Bob. Unless someone can tell me what I'm missing I will have to write my own data manager.
I resume step by step:
1 - Create a console project.
2 - Install EF using Nuget: Install-Package EntityFramework
3 - Create SalesRepresentative:
namespace EF {
public partial class SalesRepresentative {
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string CellPhone { get; set; }
}
}
4 - Create GeneralContext
namespace EF {
public class GeneralContext: DbContext {
public DbSet<SalesRepresentative> SalesRepresentatives { get; set; }
}
}
5 - So:
namespace EF {
class Program {
static void Main(string[] args) {
using (var ctx = new GeneralContext()) {
SalesRepresentative emp = new SalesRepresentative() { Name = "Prashant" };
ctx.SalesRepresentatives.Add(emp);
ctx.SaveChanges();
}
}
}
}
Note: In the App.config file (or web.config) you should customize the connection string.

Convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.IList<>' [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
In my model Account I have a property like this
public List<String> Roles { get; set; }
Later on I want to get that property but convert it IList<IApplicationUserRole<Role>>, so I have this function
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles; // how do I convert this in the specific type intended.
}
}
Here is my IApplicationUserRole
public interface IApplicationUserRole<TRoleModel> : IRole<string>
where TRoleModel : EntityModel
{
TRoleModel Role { get; set; }
String Name { get; set; }
}
I am a newbie to this thing. Looking forward for any help.
Say you have your implementing class be something like:
public class ApplicationUserRole : IApplicationUserRole<T> where T : Role
{
public ApplicationUserRole()
{
}
public User User { get; set; }
public T Role { get; set; }
}
Then, you'd do something like this:
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles
.Select(r => new ApplicationUserRole { Role = roleService.FindRoleByName(r) })
.Cast<IApplicationUserRole<Role>>()
.ToList();
}
}
Where roleService is some way of building a Role instance from the role name (which above is r)
NOTE: This being said, there is a catch in the above implementation. Since Roles is a property it should not do data access operations. So, in this case, you should create a method instead of a property.
I would start with something like this:
public IList<IApplicationUserRole<Role>> Roles
{
get
{
return _account.Roles.Select(r=>
new ApplicationUserRole<Role>() {Name = r})
.Cast<IApplicationUserRole<Role>>()
.ToList();
}
}
This assuming that you have a class that implements the IApplicationUserRole<Role> interface.
As #MartinLiversage says you can't directly convert List<T> to List<U>, you have to manually do the conversion.

How to capture value OOPS & Generic [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 8 years ago.
Improve this question
here is my code given.
class Program
{
static void Main(string[] args)
{
var _User = new User { Name="Test", Age=12 };
_User.Save();
}
}
public class DBObject<T>
{
public void Save()
{
}
}
public class User : DBObject<User>
{
public string Name { get; set; }
public int Age { get; set; }
}
i want to capture user name & age from save method ? how could i do so......plzz guide. thanks
While looking at your code, why would one want to read class specific properties in a generic method?
The only solutions i see is to use Reflection, or create an abstract base class with a before save method and call that method in de Save() method. Add a generic type constraint to the DBObject class defining that T is of the basetype. This way you can add class specific functionality to a generic method. Something like this:
public abstract class Base
{
public virtual void BeforeSave()
{
}
}
public class User : Base
{
public string Name { get; set; }
public int Age { get; set; }
public override void BeforeSave()
{
// You can access your properties here
if (this.Name.Trim() == "")
throw new Exception("Name is mandatory!")
}
}
public class DBObject<T>
where T: Base
{
public void Save()
{
T.BeforeSave();
}
}

Categories