what happens if you implement an automatic property
public string Foobar { get; set; }
and then code the corresponding variable
private string foobar = string.Empty;
Will the automatic property use this variable or does the compiler generate
an additional variable?
No, the automatic property will not use your variable. It would be just like any other field called foobar.
The name smilarity does not influence the compiler in any way.
The compiler will generate a field behind the scenes but you do not have access to the backing field of the automatic property in any way.
This post shows how things work at the IL (Intermediate Langauge, Assembly of C#) level.
The compiler won't use that variable, no. To use your variable you will have to write
private string foobar = string.Empty;
public string Foobar
{
get { return foobar; }
set { foobar = value; }
}
If you have Resharper, you can set up templates to do this. Resharper will also generate a getter from an unused private variable for you.
Why would it? Backing field doesn't have to be (and often isn't) named this way.
Related
NHibernate can be extended with new implementations of IUserType, so I can customize how a mapped property is read and stored to/from the database.
An example. If I want DB null varchar to load as "n/a" string, and "n/a" string to be stored as null.
How is this possible with EF 6.2?
I am looking for a solution that doesn't break the change-tracker.
As of EF 6.2, there is no such functionality provided out of the box by the library.
If you decide to move to EF Core instead, there you can use the HasConversion functionality.
However, in your case you still wouldn't be able to use it, because there is one caveat: it can't be used to convert null values. Null always gets converted to null. From docs:
A null value will never be passed to a value converter. A null in a database column is always a null in the entity instance, and vice-versa. This makes the implementation of conversions easier and allows them to be shared amongst nullable and non-nullable properties. See GitHub issue #13850 for more information.
In that case, I suggest that instead of a Value Conversion you configure your string property to have a Backing Field. Then, you can read/write to/from the private backing field, and then have a public property handling the null value.
public class Blog
{
private string _stringFromDb;
public string MyString { get; set; }
[BackingField(nameof(_stringFromDb))]
public string MyString
{
get { return _stringFromDb ?? "n/a"; }
}
public void SetMyString(string myString)
{
// put your validation code here
_stringFromDb = myString;
}
}
In EF 6.2 the closest you could have, as a workaround, is a [NotMapped] property that can be in charge of translating the property you load from the DB.
public string StringDB { get; set; }
[NotMapped]
public string StringConverted
{
get { return MyStringProperty ?? "n/a"; }
set { MyStringProperty = value }
}
If, in addition to this, you want to hide the property being mapped to your DB by making it private, it's not as straightforward as with EF Core's backing field, but you could follow this other answer for instructions on how to achieve it.
I am trying to initialize an Entity object (ADO.NET EF Object), but it does not allow me to choose what connection string I want to use. I need to change connection string in order to give different access levels to users.
There are no overrides in the Entities Object, just a parameterless constructor.
If anyone can give me any pointers, it is appreciated.
If you have used the designer to generate an .edmx file for you, you will have something like below:
public MyEntities() : base("name=MyEntities", "MyEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
This will by default, get the connection string from your configuration file.
What you could do in this case is set the connection string
public partial class MyEntities
{
partial void OnContextCreated()
{
//Dynamically Building a Connection String
this.Connection.ConnectionString = "myconnectionstring";
}
}
Bear in mind though that this will first use the base constructor to pull the connection string from config, then set it with your custom version, basically overriding the connection string. This is typically good when you always want a default connection string.
Another option if you want a bit more control, is pass the connection string in via the constructor as shown below:
public partial class MyEntities
{
public MyEntities(string connectionString) :
base(connectionString,"MyEntities")
{
this.OnContextCreated();
}
}
Now you are passing in the connection string down to the base class and this is the only one it will use. This does mean however that you will most often need to supply this each time.
Hope this helps...
When using code-first EntityFramework, I need one property to be set before the others - how do I specify the order that it calls the property sets, when it is creating the objects from the database?
E.g.
public class Person
{
public string Name { get; set; }
public string Something
{
get { return something; }
set
{
something = value + " for " + Name;
}
}
private string something;
}
In the code above, I need the Name property to already have been set by the time it sets the Something property.
This isn't the actual example - I know there are other ways to achieve that literally, but I'm not after those, just how I can tell EF to set Name before Something.
I am trying to understand the context of your question. I am going to make the assumptions that:
The value passed to the setter is not another calculated property
the value passed to the setter is intended to be stored in the database
If name is updated you would want Something to be updated to reflect the new name?
I think your mistake here is trying to add a derived portion to the value you are looking to store. Calculate the pretty name in another property, or on a get:
UPDATE had an example overriding the get on the Something Property, but removed as I feel it is bad practice.
public class Person
{
public string Name { get; set; }
public string Something { get; set; }
public string getFancySomething {
{ return Something + " for " + Name; }
}
}
Finally - (and here is where I could use some help as I have not run into a situation where I needed to do something like this) my guess is that you do not need to be storing the partially calculated property Something in the way you were attempting, but if you do need to, I think additional detail might help someone provide you with a better answer.
UPDATE 2
As described in my comments - not sure this would work, and it feels very wrong, but you could try something like:
modelBuilder.Entity<Person>().Ignore(x => x.Something);
and then in the setter:
public class Person
{
public string Name {
get { return Name; }
set {
Name = value;
Something = lookup();
}
}
}
Again this will depend on you needs, and would not satisfy any need to pass this value in, and I am not sure this is a great idea.
I have an enum property. I want the serialized XML for this property to be the splitted camel-case string of the enum and vice versa.
I have two functions, one is ConcatCamelCase and the other is SplitCamelCase, I want the serializer to use them accordingly, is this possible by just decorating the field with an attribute?
If no, what are the other option without having to mess with all the other fields?
You'll have to do something like this:
public class SomeClass {
[XmlIgnore]
public MyEnum MyRealProperty {get;set;}
[XmlElement("MyRealProperty")]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string MyProxyProperty
{
get {return SplitCamelCase(MyRealProperty);}
set {MyRealProperty = ConcatCamelCase(value);}
}
}
You can explicitly set the name of everything that is serialized using the XMlSerialization attributes.
[XmlRoot("theNameYouWant")]
[XmlElement("theNameYouWant")]
As far as I am aware, for the property to be saved in the database it cannot be ReadOnly.
IIdentity properties: AuthenticationType, IsAuthenticated and Name are all ReadOnly.
Is making the wrapper to the properties that need to be saved the only solution or there are better ones?
EDIT:
I might not have explained my question that well. Here is the sample code for one of the ReadOnly properties, I have added UserName property for the Entity Framework:
Public Property UserName As String
Get
Return _userName
End Get
Private Set(value As String)
userName = value
End Set
Public ReadOnly Property Name As String Implements System.Security.Principal.IIdentity.Name
Get
Return UserName
End Get
End Property
What I wanted to ask is if there is any better way of doing it.
IIdentity properties are read only but the implementation can have setters. If you are using EDMX for mapping you don't have to expose these setters as public.
Edit:
This is possible in C# so hopefully you can use similar approach with VB.NET (I can only read VB code, not write):
public interface ITest {
string Name { get; }
}
public class Test : ITest {
public string Name { get; set; }
}
The class offers setter even the interface didn't define it.
The EF persists objects, not interfaces. Your object can have whatever properties you would like it to have. You cannot add an interface to your entity model, but you can add an object type which implements that interface.