override a linq attribute c# - c#

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Gender", DbType="Int NOT NULL", UpdateCheck=UpdateCheck.Never)]
public int Gender
{
get
{
return this._Gender;
}
set
{
if ((this._Gender != value))
{
this.OnGenderChanging(value);
this.SendPropertyChanging();
this._Gender = value;
this.SendPropertyChanged("Gender");
this.OnGenderChanged();
}
}
}
there is an attribute for update check which I set it to never. But when ever I made a small change in dbml I must set this property of this field to never again. How can I override this attribute for ever in an partial class?
Update: as an example I can change dbml connection string like this, one time for ever:
partial class DataBaseDataContext : System.Data.Linq.DataContext
{
public DataBaseDataContext() :
base(ConfigurationManager.ConnectionStrings["MyConnection"].ToString())
{
OnCreated();
}
}

Open the dbml file in the designer and set Update Check for the property to the desired value. Don't modify the generated files directly, it will be overwritten.

Related

Style of generated properties Vs C#

How can I change the style of the properties that are generated by Visual studio?
This is what I get :
public int Population {
get {
return _Population;
}
set {
_Population = value;
}
}
This is what i want :
public string Population
{
get{return _Population;}
set{_Population=value;}
}
You are looking for existing propfull code snippet.
So type propfull and press Tab twice your desired format will be created.
private int _Population;
public int Population
{
get { return _Population; }
set { _Population = value; }
}
**Edited:**Control the way code is formatted after Refactor->Encapsulate Field
Please note that Language Service formats code once its added using code-snippets. Hence, one can change the formatting of the code inserted after Refactor->Encapsulate Field by changing option Leave block on single line as unchecked. Its shown in image below.

Databinding Entity Framework navigation properties - handling change

So I'm building my first larger application and I'm using WPF for Windows and stuff and Entity Framework for retrieving, updating and storing data.So far using a pattern similar to the MVVM pattern, I had a couple of issues but was able to resolve them and am quite far into design.
Also, I'm using database first approach.
But I have just ran into a brick wall that I should have anticipated. It has to do with nested properties in entities and the way changes to them are handled. Let's explain.
For the purpose of simplicity I will not be using my actual class names.
So let's say I have three entities in my EF Model: Department, Manager and PersonalInfo.
I modified my *.tt Template file so that all my entities also implement INotifyPropertyChanged interface, but only for their NON NAVIGATION properties since Navigation properties are declared as virtual and WILL be overridden by EF when their date gets set.
So let's say my generated classes look like this:
public partial class Department : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropChange(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public Department() { }
int _id;
public int ID { get { return _id; } set { _id = value; OnPropChange("ID"); } }
int _someproperty;
public int SomeProperty { get { return _someproperty; } set { _someproperty= value; OnPropChange("SomeProperty"); } }
int _managerid;
public int ManagerID { get { return _managerid; } set { _managerid = value; OnPropChange("ManagerID"); } }
public virtual Manager Manager { get; set; }
}
public partial class Manager : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropChange(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public Manager() { }
int _id;
public int ID { get { return _id; } set { _id = value; OnPropChange("ID"); } }
public virtual PersonalInfo PersonalInfo { get; set; }
}
public partial class PersonalInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropChange(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public PersonalInfo() { }
int _id;
public int ID { get { return _id; } set { _id = value; OnPropChange("ID"); } }
string _firstname;
public string FirstName { get { return _firstname; } set { _firstname = value; OnPropChange("FirstName"); } }
string _lastname;
public string LastName { get { return _lastname; } set { _lastname = value; OnPropChange("LastName"); } }
}
Now this works pretty well if I want to let's say display a list of Departments with their Managers. First I load the data into the EF Context like so
Context.Departments.Include(d => d.Manager.PersonalInfo).Load();
Departments = Context.Deparments.Local;
And than in the XAML I can do:
<DataGrid ItemsSource="{Binding Departments}" SelectedItem="{Binding CurrentDepartment, Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}"/>SomeProperty
<DataGridTextColumn Binding="{Binding SomeProperty }" Header="Property"/>
<DataGridTextColumn Binding="{Binding Manager.PersonalInfo.FirstName}" Header="FirstName"/>
<DataGridTextColumn Binding="{Binding Manager.PersonalInfo.LastName}" Header="LastNameName"/>
</DataGrid.Columns>
</DataGrid>
And all of this works wonderfully. I can add and remove items with no problems by simply removing them from Context and saving changes. Since entity sets are ObservableCollections any additions or removal from them automatically raises appropriate events which update the datagrid. I can also modify any nonnavigation property of the Department and can refresh the data in CurrentDepartment like so:
Context.Entry(CurrentDepartment).Refresh();
and it automatically refreshes the data in the datagrid.
Problems start when I change one of the navigation properties. Let's say that I opened a window in which I edited the Department, where I changed the current manager from Bob Bobington to Dave Daveston. When I return to this window calling:
Context.Entry(CurrentDepartment).Refresh();
It will only refresh non navigation properties, and First and Lastname columns will still say Bob Bobington. But that is Refresh function working as intended. But if I load the correct data into the context like this:
Context.Entry(CurrentDepartment).Reference(d=>d.Manager);
Context.Entry(CurrentDepartment.Manager).Reference(m=>m.PersonalInfo);
is still won't change the contents of the first and last name columns since they are still bound to the OLD manager. They will only refresh if the change happens on Bob Bobington instance of PersonalInfo.
I can sort of solve this level of problem by binding the column directly to Manager property, and converting Manager to text either via a ValueConverter or by overriding ToString for Manager. But that won't help since WPF won't ever be notified that Manager property has changed since changes to that property don't raise PropertyChanged event.
Navigation properties can not raise that event since even if I edited the tt template so it generates the code for the navigation property like so:
Manager _manager;
public virtual Manager Manager { get{return _manager;}
set{
_manager=value;
OnPropChange("Manager");
}
}
all this code will likely be overridden by the EF framework itself.
Sooo, what is the best thing to do in these cases? Please don't tell me that conventional wisdom is to copy the data from EF Poco classes into your own and use them. :(
UPDATE:
Here goes a potentially stupid solution for this problem. But it works.
ObservableCollection<Department> tempd = Departments;
Department temp = CurrentDepartment;
Departments = null;
CurrentDepartment = null;
Context.Entry(temp).Refresh();
Context.Entry(temp).Reference(d=>d.Manager).Load();
Context.Entry(temp.Manager).Reference(m=>m.PersonalInfo).Load();
Departments = tempd;
CurrentDepartment = temp;
As you can clearly see the key is in forcing the DataGrid to rebind itself from scratch. This way it will use no shortcuts and will rebind itself properly. BUT this method is quite silly. I shiver at the thought of having to do this to datagrids with hundreds of rows.
So I'm still waiting for a proper solution, but I'll be continuing onwards using this. Something is better than nothing.
Well, conventional wisdom is to copy the data across to another POCO, or at least make your ViewModel class peek through to an underlying Model class. You have combined your Model and ViewModel classes such that Model-based constraints (virtual methods required by your ORM) are interfering with your ViewModel-based constraints (to allow databinding, you must be able to raise events from property setters).
If your Model and ViewModel were properly separated (Separation of Concerns) then you could have your virtual methods and database-required fields on your Model (a DB persistable object) and your purely View-based functions (PropertyChanged events) on your ViewModel. Your DB code should never care about your PropertyChanged events anyway.
You can make it easier by making the ViewModel a look-through class so every property getter-setter looks like:
public string PropertyThing
{
get { return _myModel.PropertyThing; }
set { _myModel.PropertyThing = value; PropChanged("PropertyThing"); }
}
If you're already doing code generation this shouldn't be a major chore.
Alternatively, you could duplicate all the values with something like AutoMapper to separate out your Model and ViewModel to separate classes.
It's not what you wanted to hear, but your ORM and your UI are clashing and that's the sort of thing that MVVM architecture (specifically separating the Model and ViewModel) are supposed to make better.

Change the default value of a settingsvalue

id didnt find anything on Stackoverflow or on the internet, im sorry if this question was already posted (or if its simply impossible).
Is there a way to change the default value of a *.settigs-property, for example if i have the setting "USER"
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("TESTUSER")]
public string SQLServer {
get {
return ((string)(this["USER"]));
}
set {
this["USER"] = value;
}
}
would there be a way to change (at runtime) the DefaultSettingValueAttribute ("TESTUSER") to another value (i.e: "John Doe").
Thanks in advance
You can override the Properties property of the ApplicationSettingsBase class:
public override SettingsPropertyCollection Properties
{
get
{
var properties = base.Properties;
properties["SQLServer"].DefaultValue =
String.Format("John Doe {0}", DateTime.Now);
return properties;
}
}

Setting default value in entity framework - Database First

I am using Entity Framework 4.3.1, with auto-generated entities from the database.
From this, is there any way to set the default value to something? I don't want to put it in the auto-generated code since it will be overwritten.
I understand that it is possible to use partial classes, so I tried something like this, where entity is generated, and DESCRIPTION_ is the attribute I want to set to a default value.
namespace name.Models
{
public partial class ENTITY
{
public string DESCRIPTION_
{
set { _DESCRIPTION_ = "default string"; }
}
}
}
Maybe if somebody could give me an example that would be great!
The example you give means that DESCRIPTION can only ever be "default string"
You can set it in the constructor
namespace name.Models
{
public partial class ENTITY
{
private string defaultDescription = "some text";
public ENTITY() {
DESCRIPTION_ = defaultDescription;
}
}
}
or by switching your property to one with a backing field
namespace name.Models
{
public partial class ENTITY
{
private string _desc = "some default value";
public virtual string DESCRIPTION_ {get {return _desc} set {_desc = value;} }
}
}
You use OnCreated on the partial class:
public partial class ENTITY
{
partial void OnCreated()
{
DESCRIPTION_ = "default string";
}
}

Problem trying to create database for windows phone app

I'm trying to create a simple database to use sqlce in a windows phone app.
I have a base class, and another set of classes that derive from it
Here's what i got
public abstract class EntityBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
private int id;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int EntityId
{
get
{
return id;
}
set
{
if (id != value)
{
id = value;
OnPropertyChanged("Id");
}
}
}
}
[Table]
public class Derived : EntityBase
{
[Column]
public string Description
{
get;
set;
}
}
Then, I've got this class for datacontext purposes:
public class MyDataContext : DataContext
{
// Specify the connection string as a static, used in main page and app.xaml.
public static string DBConnectionString = "Data Source=isostore:/ToDo.sdf";
// Pass the connection string to the base class.
public MyDataContext(string connectionString)
: base(connectionString)
{ }
public Table<Derived> Deriveds;
}
And finally, here i'm trying to create the db :
private void Application_Launching(object sender, LaunchingEventArgs e)
{
using (MyDataContext db = new MyDataContext(MyDataContext.DBConnectionString))
{
if (db.DatabaseExists() == false)
{
//Create the database -> here's the error
db.CreateDatabase();
}
}
}
I'm getting the following error when trying to create the database :
Invalid column ID. [ EntityId ]
Yes, a very descriptive error message...
Any ideas on what's wrong? I've been tampering around with the attributes in the column but to no avail.
[EDIT] : for what i've been testing, if i put the EntityId property in the derived class, it doesn't crash. This can be 2 things.. one, that I'm missing something else in the base class, or the other one, that the column attribute for a primary key must belong to the class, and can't belong to the parent (which would be a extremely horrible design decision, we can't use inheritance???). if someone can confirm this that would be appreciated
Ok, i think i found what was happening. In this implementation of SQLCe, we need to do the following approach when using inheritance :
http://msdn.microsoft.com/en-us/library/bb399352(v=VS.100).aspx
I don't particularly like it very much, the tables that it generates aren't normalized, but well, it's true that we shouldn't be using huge and complex datastores for WP7 apps, it's more to store some basic info that's too much to handle by isolated storage on itself..
Following this approach, it worked. I have now a collection of the base class, and i can put into it any of it's derived children. Then to retrieve them back, I use the discriminator in a linq to sql query to get one derived class or another.

Categories

Resources