I have an auto generated class with a property on it. I want to add some data annotations to that property in another partial class of the same type. How would I do that?
namespace MyApp.BusinessObjects
{
[DataContract(IsReference = true)]
public partial class SomeClass: IObjectWithChangeTracker, INotifyPropertyChanged
{
[DataMember]
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
private string _name;
}
}
and in another file I have:
namespace MyApp.BusinessObjects
{
public partial class SomeClass
{
private SomeClass()
{
}
[Required]
public string Name{ get; set; }
}
}
Currently, I get an error stating that the name property already exists.
Looks like I figured out a different way similar to the link above using MetadataTypeAttribute:
namespace MyApp.BusinessObjects
{
[MetadataTypeAttribute(typeof(SomeClass.Metadata))]{
public partial class SomeClass
{
internal sealed class Metadata
{
private Metadata()
{
}
[Required]
public string Name{ get; set; }
}
}
}
I'm using the below to also support multiple foreign keys in the same table that refer to the same table. Example, the person has two parents (Father and Mother) who are both Person class.
[MetadataTypeAttribute(typeof(SomeClassCustomMetaData))]
public partial class SomeClass
{
}
public class SomeClassCustomMetaData
{
[Required]
public string Name { get; set; }
[InverseProperty("Father")]
public virtual Parent ParentClass { get; set; }
[InverseProperty("Mother")]
public virtual Parent ParentClass1 { get; set; }
}
Related
My problem is that I deserialize the incoming data and transfer it to this class using jsonproperty. but I don't want to use property name attribute that I use in jsonproperty while serializing.
example class
public class DocumentDetail
{
[JsonProperty("KAREKOD")]
public string qrCode { get; set; }
[JsonProperty("GTIN")]
public string gtinNumber { get; set; }
[JsonProperty("LOTNUMBER")]
public string lotNumber { get; set; }
}
example serialize
{
DocumentDetail docDetail=new DocumentDetail(){qrCode="123456adsfg789",gtinNumber ="123asdf548654",lotNumber ="1231231sdfg23"};
var obj=JsonConvert.SerializeObject(body);
}
example result
{
"qrCode" : "123456adsfg789",
"gtinNumber" : "123asdf548654",
"lotNumber" : "1231231sdfg23"
}
you can add a constructor to your class
public class DocumentDetail
{
public string qrCode { get; set; }
public string gtinNumber { get; set; }
[JsonProperty("lotNumber")] // optional, you can assign any name for serialization
public string lotNumber { get; set; }
[Newtonsoft.Json.JsonConstructor]
public DocumentDetail( string KAREKOD,string GTIN, string LOTNUMBER)
{
qrCode=KAREKOD;
gtinNumber=GTIN;
lotNumber=LOTNUMBER;
}
public DocumentDetail() {}
}
and you don't need to include all properties in the constructor, just include the properties that need different names for a serialization and a deserialiazation.
This worked for me
public class Foo
{
private string bar;
public string IncomingBar { set { bar = value; } }
public string OutgoingBar { get { return bar; } }
}
Suppose I have this class:
public class MyClass
{
public string PropertyOne;
{
get;set;
}
public MyClass Country;
{
get;set;
}
}
I need to omit the properties having type of it's own class.
In my Code snippet, Country property should be omitted for my data model. How can I do that?
You can use Data Annotations to exclude a property from the model.
using System.ComponentModel.DataAnnotations.Schema;
public class MyClass
{
public string PropertyOne { get; set; }
[NotMapped]
public MyClass Country { get; set; }
}
I am invoking a method in my constructor like below.Is this the right way to do to set properties based on some validations.Please suggest.
public class Asset
{
public Asset(string id)
{
SetStorageId(id);
}
public string AssetId { get; set; }
public string UtilId { get; set; }
public string MappingId { get; set; }
public bool IsActive { get; set; }
private void SetStorageId(string id)
{
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
AssetId = id;
}
else
{
UtilId = id;
}
}
}
In my opinion your design should be like below,
You should abstract common items to base class and create specific class inheriting this,
and decide from client(consumer) which instance do you need and construct it
public class AssetBase
{
public string MappingId { get; set; }
public bool IsActive { get; set; }
}
public class Asset : AssetBase
{
public string AssetId { get; set; }
}
public class Util : AssetBase
{
public string UtilId { get; set; }
}
static void Main(string[] args)
{
string id = Console.ReadLine();
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
Asset asset = new Asset();
asset.AssetId = id;
}
else
{
Util util = new Util();
util.UtilId = id;
}
}
simply try this
public class Asset
{
private string id;
public string AssetId { get; set; }
public string UtilId { get; set; }
public string Id
{
set
{
if (Regex.Match(value, "^[A-Z][a-zA-Z]*$").Success)
{
this.id = value;
}
else
{
UtilId = value;
}
}
get
{
return id;
}
}
}
When you create a property in c#, a private variable is created for that property on compile time. When you try to set the Id property in the code above the Id you pass goes into the value keyword and you can perform your validations on the value keyword and set your property accordingly.
No need to complicate your code with set methods, constructors or deriving classes
or you can even use data annotations which is a more elegant way https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx#Properties
using System.ComponentModel.DataAnnotations;
public class Asset
{
[RegularExpression("^[A-Z][a-zA-Z]*$")]
public string Id { get; set; }
}
It's not wrong. It can possibly grow to be a little confusing. Maybe you can make it clearer by moving the bod of SetStorageId to the constructor. Perhaps there is no need to complicate with subclassing, relative to other code within the project.
I am trying to implement a hierarchical inheritance structure in Entity Framework, specifically for settings. For example, lets say we have user preferences:
public class StorePreference: Preference { }
public class UserPreference : Preference { }
public class Preference {
public string BackgroundColor { get; set; }
public ContactMethod ContactMethod { get; set; }
}
public enum ContactMethod {
SMS,
Email
}
I'd like it so that if I lookup the user's preferences. If the user doesn't exist or the property value is null, it looks up the parent (store) default preferences.
Ideally, i'd like it to work similar to abstract inheritance:
public class UserPreference : StorePreference {
private string _backgroundColor;
public string BackgroundColor {
get {
if (this._backgroundColor == null)
return base;
return this._backgroundColor;
}
set { this._backgroundColor = value; }
}
}
If I were to write this as a SQL query, it'd be a CROSS APPLY with a CASE statement:
SELECT
CASE WHEN User.BackgroundColor == null THEN Store.BackgroundColor ELSE User.BackgroundColor END BackgroundColor,
CASE WHEN User.ContactMethod == null THEN Store.ContactMethod ELSE User.ContactMethod END ContactMethod
FROM UserPreference User
CROSS APPLY StorePreference Store
WHERE UserPreference.UserId = #UserId
Is there a way I can achieve loading this in EF?
In your base class add default property values:
public class Preference {
public string BackgroundColor { get; set; } = "Red";
public ContactMethod ContactMethod { get; set; } = ContactMethod.SMS;
}
Something like this to set from database:
public class StorePreference : Preference { }
public class UserPreference : Preference { }
public class Preference {
public Preference() {
BackgroundColor = DefaultPreference.BackgroundColor;
ContactMethod = DefaultPreference.ContactMethod;
}
public string BackgroundColor { get; set; }
public ContactMethod ContactMethod { get; set; }
public DefaultPreference DefaultPreference { get; set; }
}
public class DefaultPreference {
public string BackgroundColor { get; set; }
public ContactMethod ContactMethod { get; set; }
}
As long as the properties are public, entity won't have a problem pulling the data from another table as the default. You would need to create a private field to hold the data if you used a setter:
public class ChildTable : EntityBase {
private string _someCategory;
[Key]
[Column(name: "CHILD_ID")]
public override int Id { get; protected set; }
[Column(name: "SOME_CATEGORY")]
public string SomeCategory {
get { return _someCategory; }
set { _someCategory = value ?? ParentTable.SomeCategory; }
}
[ForeignKey("ParentTable")]
[Column(name: "PARENT_ID")]
public int ParentTableId { get; set; }
public virtual ParentTable ParentTable { get; set; }
}
This is just an alternative to a constructor, if you need more control over the setter logic, otherwise Austin's answer would be simpler to implement
I have the below code in my Application.
public class GeneralInfo
{
private string _id;
private string _name;
public string id
{
set
{
_id = value;
}
get
{
return _id;
}
}
public string name
{
set
{
_name = value;
}
get
{
return _name;
}
}
}
public class SecureInfo
{
private string _password;
public string password
{
set
{
_password = value;
}
get
{
return _password;
}
}
}
public class User
{
}
I need to apply multiple inheritance in the above code ie. the classes GeneralInfo,SecureInfo properties should be accessible in the user class.
I know using interface Multiple inheritance can be achieved. But i need to define the properties in the base class which is restricted in Interface.
How I can achieve this?
C# does not support multiple inheritance. However you can achieve this via multiple interfaces.
public interface ISecureInfo
{
}
public interface IGeneralInfo
{
}
public class UserClass : ISecureInfo, IGeneralInfo {
}
You probably better off encapsulating the data in the class rather than trying to use something to do multiple inheritance here. See this question for some arguments for this.
You can achieve this through interface based inheritance:
public interface IGeneralInfo
{
String Id { get; set; }
String Name { get; set; }
}
public interface ISecureInfo
String Password { get; set; }
}
public class User : IGeneralInfo, ISecureInfo
{
// Implementation of IGeneralInfo
public String Id { get; set; }
public String Name { get; set; }
// Implementation of ISecureInfo
public String Password { get; set; }
}
Or, going one step further, through composition:
public interface IGeneralInfo
{
String Id { get; set; }
String Name { get; set; }
}
public class GeneralInfo : IGeneralInfo
{
public String Id { get; set; }
public String Name { get; set; }
}
public interface ISecureInfo
String Password { get; set; }
}
public class SecureInfo : IGeneralInfo
{
public String Password { get; set; }
}
public class User : IGeneralInfo, ISecureInfo
{
private GeneralInfo generalInfo = new GeneralInfo();
private SecureInfo secureInfo = new SecureInfo();
public String Id {
get { return generalInfo.Id; }
set { generalInfo.Id = value; }
}
public String Name {
get { return generalInfo.Name; }
set { generalInfo.Name = value; }
}
public String Password {
get { return secureInfo.Password; }
set { secureInfo.Password = value; }
}
}
From your sample description, encapsulation might be what you might want to use:
public class Info{
GeneralInfo general;
SecureInfo secure;
...
}
You cannot do multiple inheritance in C# because it is not supported like C++. In C# you can use interfaces for it and implement method and properties. For sample, you could have a base class
public abstract class Entity
{
public string Name { get; set; }
}
You also could have some interfaces:
public interface IPrint
{
void Print();
}
public interface IGenerate
{
void Generate();
}
And use it like multiples inheritance (but it is not, it is just a single inheritance and interfaces)
public class User : Entity, IPrint, IGenerate
{
public void Print()
{
// some code
// here you could access Name property, because it is on base class Entity
}
public void Generate()
{
// some code
}
}
And you could instance it using the abstractions:
Entity e = new User();
IPrint p = new User();
IGenerate g = new User();
User u = new User();
If you need implementations, you could do a hiearachy inherits, for sample:
User inherit from Person that inherit from Entity.
public class Entity
{
public int Id { get; set; }
public void Method()
{
// some code
}
}
public class Person : Entity
{
public string Name { get; set; }
public void AnotherMethod()
{
// some code
}
}
public class User : Person
{
public string Password { get; set; }
public bool CheckUser(string name, string passworkd)
{
// some code
}
}
I think the best would be to seperate the implementation of the interfaces and the real class you have at the end.
What I mean is something like the Bridge Pattern.
Your class (that will implement several interfaces) will just deleagte the method calls to the real implementation, that you can have in a seperate place and only once.
You could also use an approach like this. You would get to the same point than if you would be using multiple inheritance. That way, you could inherit only Entity if you don't need the SecureInfo stuff (i.e. for books and other stuff). Still, I think composition would do better in this case as others say...
class User : SecuredEntity { }
abstract class SecuredEntity : Entity, ISecureInfo
{
public string Password { get; set; }
}
abstract class Entity : IGeneralInfo
{
public string ID { get; set; }
public string Name { get; set; }
}
interface IGeneralInfo
{
string ID { get; set; }
string Name { get; set; }
}
interface ISecureInfo
{
string Password { get; set; }
}