So my code seems to be breaking when I save changes. I'm not able to update the table in my local database. Looking for help please. I apologize if this was more than what is being asked of me. I don't really understand how linq is working and what I need to do in order to do basic SQL commands.
private void addUser()
{
try
{
var t = new tUser
{
Username = "test",
Password = "Password",
Email = "test#test.com",
Approved = true,
UserRoleID = 1,
First_Name = "test",
Last_Name = "test",
};
this.db.AddTotUsers(t);
this.db.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
Here is the class generated for tUser
using System;
using System.ComponentModel;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Serialization;
[assembly: EdmSchemaAttribute()]
namespace AVOSoftware
{
#region Contexts
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public partial class Database1Entities : ObjectContext
{
#region Constructors
/// <summary>
/// Initializes a new Database1Entities object using the connection string found in the 'Database1Entities' section of the application configuration file.
/// </summary>
public Database1Entities() : base("name=Database1Entities", "Database1Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new Database1Entities object.
/// </summary>
public Database1Entities(string connectionString) : base(connectionString, "Database1Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new Database1Entities object.
/// </summary>
public Database1Entities(EntityConnection connection) : base(connection, "Database1Entities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
#endregion
#region Partial Methods
partial void OnContextCreated();
#endregion
#region ObjectSet Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<tUser> tUsers
{
get
{
if ((_tUsers == null))
{
_tUsers = base.CreateObjectSet<tUser>("tUsers");
}
return _tUsers;
}
}
private ObjectSet<tUser> _tUsers;
#endregion
#region AddTo Methods
/// <summary>
/// Deprecated Method for adding a new object to the tUsers EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddTotUsers(tUser tUser)
{
base.AddObject("tUsers", tUser);
}
#endregion
}
#endregion
#region Entities
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="Database1Model", Name="tUser")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class tUser : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new tUser object.
/// </summary>
/// <param name="userID">Initial value of the UserID property.</param>
/// <param name="username">Initial value of the Username property.</param>
/// <param name="password">Initial value of the Password property.</param>
/// <param name="userRoleID">Initial value of the UserRoleID property.</param>
/// <param name="first_Name">Initial value of the First_Name property.</param>
/// <param name="last_Name">Initial value of the Last_Name property.</param>
/// <param name="approved">Initial value of the Approved property.</param>
/// <param name="email">Initial value of the Email property.</param>
public static tUser CreatetUser(global::System.Int64 userID, global::System.String username, global::System.String password, global::System.Int32 userRoleID, global::System.String first_Name, global::System.String last_Name, global::System.Boolean approved, global::System.String email)
{
tUser tUser = new tUser();
tUser.UserID = userID;
tUser.Username = username;
tUser.Password = password;
tUser.UserRoleID = userRoleID;
tUser.First_Name = first_Name;
tUser.Last_Name = last_Name;
tUser.Approved = approved;
tUser.Email = email;
return tUser;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int64 UserID
{
get
{
return _UserID;
}
set
{
if (_UserID != value)
{
OnUserIDChanging(value);
ReportPropertyChanging("UserID");
_UserID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserID");
OnUserIDChanged();
}
}
}
private global::System.Int64 _UserID;
partial void OnUserIDChanging(global::System.Int64 value);
partial void OnUserIDChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Username
{
get
{
return _Username;
}
set
{
OnUsernameChanging(value);
ReportPropertyChanging("Username");
_Username = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Username");
OnUsernameChanged();
}
}
private global::System.String _Username;
partial void OnUsernameChanging(global::System.String value);
partial void OnUsernameChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Password
{
get
{
return _Password;
}
set
{
OnPasswordChanging(value);
ReportPropertyChanging("Password");
_Password = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Password");
OnPasswordChanged();
}
}
private global::System.String _Password;
partial void OnPasswordChanging(global::System.String value);
partial void OnPasswordChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 UserRoleID
{
get
{
return _UserRoleID;
}
set
{
OnUserRoleIDChanging(value);
ReportPropertyChanging("UserRoleID");
_UserRoleID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("UserRoleID");
OnUserRoleIDChanged();
}
}
private global::System.Int32 _UserRoleID;
partial void OnUserRoleIDChanging(global::System.Int32 value);
partial void OnUserRoleIDChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String First_Name
{
get
{
return _First_Name;
}
set
{
OnFirst_NameChanging(value);
ReportPropertyChanging("First_Name");
_First_Name = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("First_Name");
OnFirst_NameChanged();
}
}
private global::System.String _First_Name;
partial void OnFirst_NameChanging(global::System.String value);
partial void OnFirst_NameChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Last_Name
{
get
{
return _Last_Name;
}
set
{
OnLast_NameChanging(value);
ReportPropertyChanging("Last_Name");
_Last_Name = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Last_Name");
OnLast_NameChanged();
}
}
private global::System.String _Last_Name;
partial void OnLast_NameChanging(global::System.String value);
partial void OnLast_NameChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Boolean Approved
{
get
{
return _Approved;
}
set
{
OnApprovedChanging(value);
ReportPropertyChanging("Approved");
_Approved = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Approved");
OnApprovedChanged();
}
}
private global::System.Boolean _Approved;
partial void OnApprovedChanging(global::System.Boolean value);
partial void OnApprovedChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Email
{
get
{
return _Email;
}
set
{
OnEmailChanging(value);
ReportPropertyChanging("Email");
_Email = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("Email");
OnEmailChanged();
}
}
private global::System.String _Email;
partial void OnEmailChanging(global::System.String value);
partial void OnEmailChanged();
#endregion
}
#endregion
}
Here is the Exception I'm getting
" Message "Server-generated keys and server-generated values are not supported by SQL Server Compact." string
"
Looks to me like SQL Server Compact edition doesn't support auto generated keys. You'll either need to increment UserId yourself and supply the value or get a more feature-rich version of SQL Server. I'm pretty sure SQL Server Express can do it.
You are using a very old version of Entity Framework, upgrade to version 5 or later and SQL Server Compact server generated keys (IDENTITY) columns will work for you
I'm using Entity Framework in my application with ChangeTracking Entities so I can have an Audit Log in my database for every Add, Modification, Delete (ColumnName, OriginalValue, NewValue, etc).
There are some functions that I'm not going to use Entity Framework because is very slow, for example bulk insert / update and other scenarios, instead I will user ADO.NET with Stored Procedures.
In order to keep tracking changes on both Entity Framework and ADO.NET I was thinking on use a Base Class for custom classes that will be populated from DataReaders and will need to track changes on those classes so I came up with:
public class NotifyPropertyChangeObject : INotifyPropertyChanged
{
/// <summary>
/// Track changes or not.
/// If we're working with DTOs and we fill up the DTO in the DAL we should not be tracking changes.
/// </summary>
private bool trackChanges = false;
/// <summary>
/// Changes to the object
/// </summary>
public List<TrackChange> Changes { get; private set; }
/// <summary>
/// Is the object dirty or not?
/// </summary>
public bool IsDirty
{
get { return Changes.Count > 0; }
set { ; }
}
/// <summary>
/// Event required for INotifyPropertyChanged
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// This constructor will initialize the change tracking
/// </summary>
public NotifyPropertyChangeObject()
{
// Change tracking default
trackChanges = true;
// New change tracking dictionary
Changes = new List<TrackChange>();
}
/// <summary>
/// Reset the object to non-dirty
/// </summary>
public void Reset()
{
Changes.Clear();
}
/// <summary>
/// Start tracking changes
/// </summary>
public void StartTracking()
{
trackChanges = true;
}
/// <summary>
/// Stop tracking changes
/// </summary>
public void StopTracking()
{
trackChanges = false;
}
/// <summary>
/// Change the property if required and throw event
/// </summary>
/// <param name="variable"></param>
/// <param name="property"></param>
/// <param name="value"></param>
public void ApplyPropertyChange<T, F>(ref F field, Expression<Func<T, object>> property, F value)
{
// Only do this if the value changes
if (field == null || !field.Equals(value))
{
// Get the property
var propertyExpression = GetMemberExpression(property);
if (propertyExpression == null)
throw new InvalidOperationException("You must specify a property");
// Property name
string propertyName = propertyExpression.Member.Name;
// If change tracking is enabled, we can track the changes...
if (trackChanges)
{
// Change tracking
var track = Changes.Where(c => c.Name == propertyName).FirstOrDefault();
if (track == null)
{
track = new TrackChange();
track.Name = propertyName;
track.Original = field;
track.Value = value;
Changes.Add(track);
}
else
{
track.Name = propertyName;
track.Original = field;
track.Value = value;
}
//Changes[propertyName] = value;
// Notify change
NotifyPropertyChanged(propertyName);
}
// Set the value
field = value;
}
}
/// <summary>
/// Get member expression
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
public MemberExpression GetMemberExpression<T>(Expression<Func<T, object>> expression)
{
// Default expression
MemberExpression memberExpression = null;
// Convert
if (expression.Body.NodeType == ExpressionType.Convert)
{
var body = (UnaryExpression)expression.Body;
memberExpression = body.Operand as MemberExpression;
}
// Member access
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}
// Not a member access
if (memberExpression == null)
throw new ArgumentException("Not a member access", "expression");
// Return the member expression
return memberExpression;
}
/// <summary>
/// The property has changed
/// </summary>
/// <param name="propertyName"></param>
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Convert the changes to an XML string
/// </summary>
/// <returns></returns>
public string ChangesToXml()
{
// Prepare base objects
XDeclaration declaration = new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty);
XElement root = new XElement("Changes");
// Create document
XDocument document = new XDocument(declaration, root);
// Add changes to the document
// TODO: If it's an object, maybe do some other things
//foreach (KeyValuePair<string, object> change in Changes)
// root.Add(new XElement(change.Key, change.Value));
// Get the XML
return document.Document.ToString();
}
}
public class TrackChange
{
public string Name { get; set; }
public object Original { get; set; }
public object Value { get; set; }
}
That way I can keep my Audit Log functionality on both Data Context.
When saving data using ADO.NET I will have a function that will convert my Changes into Stored Procedures parameters so I can save into my AuditLog table.
Does anyone know if this is a good alternative?
I have a class like so:
public class CompanyData
{
# region Properties
/// <summary>
/// string CompanyNumber
/// </summary>
private string strCompanyNumber;
/// <summary>
/// string CompanyName
/// </summary>
private string strCompanyName;
[Info("companynumber")]
public string CompanyNumber
{
get
{
return this.strCompanyNumber;
}
set
{
this.strCompanyNumber = value;
}
}
/// <summary>
/// Gets or sets CompanyName
/// </summary>
[Info("companyName")]
public string CompanyName
{
get
{
return this.strCompanyName;
}
set
{
this.strCompanyName = value;
}
}
/// <summary>
/// Initializes a new instance of the CompanyData class
/// </summary>
public CompanyData()
{
}
/// <summary>
/// Initializes a new instance of the CompanyData class
/// </summary>
/// <param name="other"> object company data</param>
public CompanyData(CompanyData other)
{
this.Init(other);
}
/// <summary>
/// sets the Company data attributes
/// </summary>
/// <param name="other">object company data</param>
protected void Init(CompanyData other)
{
this.CompanyNumber = other.CompanyNumber;
this.CompanyName = other.CompanyName;
}
/// <summary>
/// Getting array of entity properties
/// </summary>
/// <returns>An array of PropertyInformation</returns>
public PropertyInfo[] GetEntityProperties()
{
PropertyInfo[] thisPropertyInfo;
thisPropertyInfo = this.GetType().GetProperties();
return thisPropertyInfo;
}
}
A csv file is read and a collection of CompanyData objects is created
In this method I am trying to get properties and values:
private void GetPropertiesAndValues(List<CompanyData> resList)
{
foreach (CompanyData resRow in resList)
{
this.getProperties = resRow.ExternalSyncEntity.GetEntityProperties();
this.getValues = resRow.ExternalSyncEntity.GetEntityValue(resRow.ExternalSyncEntity);
}
}
Here's the problem, for the first object the GetEntityProperties() returns the CompanyNumber as the first element in the array. For the remaining objects it returns CompanyName as the first element.
Why is the sequence not consistent?
Regards.
The Type.GetProperties() does not return ordered result.
The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.
If you want to use ordered/consistent result, it is better to sort the returned array.
As you can likely see from the title, I am about to ask something which has been asked many times before. But still, after reading all these other questions, I cannot find a decent solution to my problem.
I have a model class with basic validation:
partial class Player : IDataErrorInfo
{
public bool CanSave { get; set; }
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Firstname")
{
if (String.IsNullOrWhiteSpace(Firstname))
{
result = "Geef een voornaam in";
}
}
if (columnName == "Lastname")
{
if (String.IsNullOrWhiteSpace(Lastname))
{
result = "Geef een familienaam in";
}
}
if (columnName == "Email")
{
try
{
MailAddress email = new MailAddress(Email);
}
catch (FormatException)
{
result = "Geef een geldig e-mailadres in";
}
}
if (columnName == "Birthdate")
{
if (Birthdate.Value.Date >= DateTime.Now.Date)
{
result = "Geef een geldige geboortedatum in";
}
}
CanSave = true; // this line is wrong
return result;
}
}
public string Error { get { throw new NotImplementedException();} }
}
This validation is done everytime the property changes (so everytime the user types a character in the textbox):
<TextBox Text="{Binding CurrentPlayer.Firstname, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="137" IsEnabled="{Binding Editing}" Grid.Row="1"/>
This works perfect. The validation occurs (the PropertyChanged code for the binding is done in the VM on the CurrentPlayer property, which is an object of Player).
What I would like to do now is disable the save button when the validation fails.
First of all, the easiest solutions seems to be found in this thread:
Enable Disable save button during Validation using IDataErrorInfo
If I want to follow the accepted solution, I'd have to write my
validation code twice, as I cannot simply use the indexer. Writing
double code is absolutely not what I want, so that's not a solution
to my problem.
The second answer on that thread sounded very promising as first,
but the problem is that I have multiple fields that have to be
validated. That way, everything relies on the last checked property
(so if that field is filled in correctly, CanSave will be true, even
though there are other fields which are still invalid).
One more solution I've found is using an ErrorCount property. But as I'm validating at each property change (and so at each typed character), this isn't possible too - how could I know when to increase/decrease the ErrorCount?
What would be the best way to solve this problem?
Thanks
This article http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validating-with-the-idataerrorinfo-interface-cs moves the individual validation into the properties:
public partial class Player : IDataErrorInfo
{
Dictionary<string, string> _errorInfo;
public Player()
{
_errorInfo = new Dictionary<string, string>();
}
public bool CanSave { get { return _errorInfo.Count == 0; }
public string this[string columnName]
{
get
{
return _errorInfo.ContainsKey(columnName) ? _errorInfo[columnName] : null;
}
}
public string FirstName
{
get { return _firstName;}
set
{
if (String.IsNullOrWhiteSpace(value))
_errorInfo.AddOrUpdate("FirstName", "Geef een voornaam in");
else
{
_errorInfo.Remove("FirstName");
_firstName = value;
}
}
}
}
(you would have to handle the Dictionary AddOrUpdate extension method). This is similar to your error count idea.
I've implemented the map approach shown in my comment above, in C# this is called a Dictionary in which I am using anonymous methods to do the validation:
partial class Player : IDataErrorInfo
{
private delegate string Validation(string value);
private Dictionary<string, Validation> columnValidations;
public List<string> Errors;
public Player()
{
columnValidations = new Dictionary<string, Validation>();
columnValidations["Firstname"] = delegate (string value) {
return String.IsNullOrWhiteSpace(Firstname) ? "Geef een voornaam in" : null;
}; // Add the others...
errors = new List<string>();
}
public bool CanSave { get { return Errors.Count == 0; } }
public string this[string columnName]
{
get { return this.GetProperty(columnName); }
set
{
var error = columnValidations[columnName](value);
if (String.IsNullOrWhiteSpace(error))
errors.Add(error);
else
this.SetProperty(columnName, value);
}
}
}
This approach works with Data Annotations. You can also bind the "IsValid" property to a Save button to enable/disable.
public abstract class ObservableBase : INotifyPropertyChanged, IDataErrorInfo
{
#region Members
private readonly Dictionary<string, string> errors = new Dictionary<string, string>();
#endregion
#region Events
/// <summary>
/// Property Changed Event
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Protected Methods
/// <summary>
/// Get the string name for the property
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
protected string GetPropertyName<T>(Expression<Func<T>> expression)
{
var memberExpression = (MemberExpression) expression.Body;
return memberExpression.Member.Name;
}
/// <summary>
/// Notify Property Changed (Shorted method name)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"></param>
protected virtual void Notify<T>(Expression<Func<T>> expression)
{
string propertyName = this.GetPropertyName(expression);
PropertyChangedEventHandler handler = this.PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Called when [property changed].
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression">The expression.</param>
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> expression)
{
string propertyName = this.GetPropertyName(expression);
PropertyChangedEventHandler handler = this.PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Properties
/// <summary>
/// Gets an error message indicating what is wrong with this object.
/// </summary>
public string Error => null;
/// <summary>
/// Returns true if ... is valid.
/// </summary>
/// <value>
/// <c>true</c> if this instance is valid; otherwise, <c>false</c>.
/// </value>
public bool IsValid => this.errors.Count == 0;
#endregion
#region Indexer
/// <summary>
/// Gets the <see cref="System.String"/> with the specified column name.
/// </summary>
/// <value>
/// The <see cref="System.String"/>.
/// </value>
/// <param name="columnName">Name of the column.</param>
/// <returns></returns>
public string this[string columnName]
{
get
{
var validationResults = new List<ValidationResult>();
string error = null;
if (Validator.TryValidateProperty(GetType().GetProperty(columnName).GetValue(this), new ValidationContext(this) { MemberName = columnName }, validationResults))
{
this.errors.Remove(columnName);
}
else
{
error = validationResults.First().ErrorMessage;
if (this.errors.ContainsKey(columnName))
{
this.errors[columnName] = error;
}
else
{
this.errors.Add(columnName, error);
}
}
this.OnPropertyChanged(() => this.IsValid);
return error;
}
}
#endregion
}
Somehow my entity data context does not update database..
In .Net framework I did the following:
Created entity model like here: http://msdn.microsoft.com/en-us/library/bb399739(v=vs.90) with the table = entity named "Level".
Added in code new context for this model:
Main_dataBaseEntities context;
//...
context = new Main_dataBaseEntities;
Added new object of the "Level" entity with Path property:
var z = new Level {Path = "zPath"};
context.Level.AddObject(z);
Saved changes:
context.SaveChanges();
Databases table shows nothing.. How can I add new item ?))
My Entity class created by Entity framework on the base of database is as follows:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Runtime.Serialization;
[assembly: EdmSchemaAttribute()]
#region EDM Relationship Metadata
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Terminals_Brokers", "Broker", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Broker), "Terminal", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Terminal), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Clients_Terminals", "Terminal", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Terminal), "Client", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Client), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_ClientsTickers_Clients", "Client", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Client), "ClientTicker", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.ClientTicker), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Risks_Clients", "Client", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Client), "Risk", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Risk), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_ClientsTickers_Tickers", "Ticker", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Ticker), "ClientTicker", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.ClientTicker), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Tickers_Currencies", "Currency", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Currency), "Ticker", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Ticker), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Levels_Strategies", "Strategy", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Strategy), "Level", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Level), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Levels_Tickers", "Ticker", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Ticker), "Level", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Level), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Transactions_Levels", "Level", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Level), "Transaction", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Transaction), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Risks_Strategies", "Strategy", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Strategy), "Risk", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Risk), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Risks_Tickers", "Ticker", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Ticker), "Risk", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Risk), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Transaction_Risk", "Risk", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Risk), "Transaction", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Transaction), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Transactions_Statuses", "Status", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.Status), "Transaction", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Transaction), true)]
[assembly: EdmRelationshipAttribute("Main_dataBaseModel", "FK_Terminals_TerminalTypes", "TerminalType", System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(trust_manager_v_1._0.TerminalType), "Terminal", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(trust_manager_v_1._0.Terminal), true)]
#endregion
namespace trust_manager_v_1._0
{
#region Contexts
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public partial class Main_dataBaseEntities : ObjectContext
{
#region Constructors
/// <summary>
/// Initializes a new Main_dataBaseEntities object using the connection string found in the 'Main_dataBaseEntities' section of the application configuration file.
/// </summary>
public Main_dataBaseEntities() : base("name=Main_dataBaseEntities", "Main_dataBaseEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new Main_dataBaseEntities object.
/// </summary>
public Main_dataBaseEntities(string connectionString) : base(connectionString, "Main_dataBaseEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new Main_dataBaseEntities object.
/// </summary>
public Main_dataBaseEntities(EntityConnection connection) : base(connection, "Main_dataBaseEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
#endregion
#region Partial Methods
partial void OnContextCreated();
#endregion
#region ObjectSet Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Broker> Broker
{
get
{
if ((_Broker == null))
{
_Broker = base.CreateObjectSet<Broker>("Broker");
}
return _Broker;
}
}
private ObjectSet<Broker> _Broker;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Client> Client
{
get
{
if ((_Client == null))
{
_Client = base.CreateObjectSet<Client>("Client");
}
return _Client;
}
}
private ObjectSet<Client> _Client;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<ClientTicker> ClientTicker
{
get
{
if ((_ClientTicker == null))
{
_ClientTicker = base.CreateObjectSet<ClientTicker>("ClientTicker");
}
return _ClientTicker;
}
}
private ObjectSet<ClientTicker> _ClientTicker;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Currency> Currency
{
get
{
if ((_Currency == null))
{
_Currency = base.CreateObjectSet<Currency>("Currency");
}
return _Currency;
}
}
private ObjectSet<Currency> _Currency;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Level> Level
{
get
{
if ((_Level == null))
{
_Level = base.CreateObjectSet<Level>("Level");
}
return _Level;
}
}
private ObjectSet<Level> _Level;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Risk> Risk
{
get
{
if ((_Risk == null))
{
_Risk = base.CreateObjectSet<Risk>("Risk");
}
return _Risk;
}
}
private ObjectSet<Risk> _Risk;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Status> Status
{
get
{
if ((_Status == null))
{
_Status = base.CreateObjectSet<Status>("Status");
}
return _Status;
}
}
private ObjectSet<Status> _Status;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Strategy> Strategy
{
get
{
if ((_Strategy == null))
{
_Strategy = base.CreateObjectSet<Strategy>("Strategy");
}
return _Strategy;
}
}
private ObjectSet<Strategy> _Strategy;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<sysdiagrams> sysdiagrams
{
get
{
if ((_sysdiagrams == null))
{
_sysdiagrams = base.CreateObjectSet<sysdiagrams>("sysdiagrams");
}
return _sysdiagrams;
}
}
private ObjectSet<sysdiagrams> _sysdiagrams;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Terminal> Terminal
{
get
{
if ((_Terminal == null))
{
_Terminal = base.CreateObjectSet<Terminal>("Terminal");
}
return _Terminal;
}
}
private ObjectSet<Terminal> _Terminal;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<TerminalType> TerminalType
{
get
{
if ((_TerminalType == null))
{
_TerminalType = base.CreateObjectSet<TerminalType>("TerminalType");
}
return _TerminalType;
}
}
private ObjectSet<TerminalType> _TerminalType;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Ticker> Ticker
{
get
{
if ((_Ticker == null))
{
_Ticker = base.CreateObjectSet<Ticker>("Ticker");
}
return _Ticker;
}
}
private ObjectSet<Ticker> _Ticker;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Transaction> Transaction
{
get
{
if ((_Transaction == null))
{
_Transaction = base.CreateObjectSet<Transaction>("Transaction");
}
return _Transaction;
}
}
private ObjectSet<Transaction> _Transaction;
#endregion
#region AddTo Methods
/// <summary>
/// Deprecated Method for adding a new object to the Broker EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToBroker(Broker broker)
{
base.AddObject("Broker", broker);
}
/// <summary>
/// Deprecated Method for adding a new object to the Client EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToClient(Client client)
{
base.AddObject("Client", client);
}
/// <summary>
/// Deprecated Method for adding a new object to the ClientTicker EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToClientTicker(ClientTicker clientTicker)
{
base.AddObject("ClientTicker", clientTicker);
}
/// <summary>
/// Deprecated Method for adding a new object to the Currency EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToCurrency(Currency currency)
{
base.AddObject("Currency", currency);
}
/// <summary>
/// Deprecated Method for adding a new object to the Level EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToLevel(Level level)
{
base.AddObject("Level", level);
}
/// <summary>
/// Deprecated Method for adding a new object to the Risk EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToRisk(Risk risk)
{
base.AddObject("Risk", risk);
}
/// <summary>
/// Deprecated Method for adding a new object to the Status EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToStatus(Status status)
{
base.AddObject("Status", status);
}
/// <summary>
/// Deprecated Method for adding a new object to the Strategy EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToStrategy(Strategy strategy)
{
base.AddObject("Strategy", strategy);
}
/// <summary>
/// Deprecated Method for adding a new object to the sysdiagrams EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddTosysdiagrams(sysdiagrams sysdiagrams)
{
base.AddObject("sysdiagrams", sysdiagrams);
}
/// <summary>
/// Deprecated Method for adding a new object to the Terminal EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToTerminal(Terminal terminal)
{
base.AddObject("Terminal", terminal);
}
/// <summary>
/// Deprecated Method for adding a new object to the TerminalType EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToTerminalType(TerminalType terminalType)
{
base.AddObject("TerminalType", terminalType);
}
/// <summary>
/// Deprecated Method for adding a new object to the Ticker EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToTicker(Ticker ticker)
{
base.AddObject("Ticker", ticker);
}
/// <summary>
/// Deprecated Method for adding a new object to the Transaction EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead.
/// </summary>
public void AddToTransaction(Transaction transaction)
{
base.AddObject("Transaction", transaction);
}
#endregion
}
#endregion
#region Entities
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="Main_dataBaseModel", Name="Broker")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Broker : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Broker object.
/// </summary>
/// <param name="id">Initial value of the ID property.</param>
public static Broker CreateBroker(global::System.Guid id)
{
Broker broker = new Broker();
broker.ID = id;
return broker;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Guid ID
{
get
{
return _ID;
}
set
{
if (_ID != value)
{
OnIDChanging(value);
ReportPropertyChanging("ID");
_ID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ID");
OnIDChanged();
}
}
}
private global::System.Guid _ID;
partial void OnIDChanging(global::System.Guid value);
partial void OnIDChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Name
{
get
{
return _Name;
}
set
{
OnNameChanging(value);
ReportPropertyChanging("Name");
_Name = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Name");
OnNameChanged();
}
}
private global::System.String _Name;
partial void OnNameChanging(global::System.String value);
partial void OnNameChanged();
#endregion
#region Navigation Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("Main_dataBaseModel", "FK_Terminals_Brokers", "Terminal")]
public EntityCollection<Terminal> Terminal
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Terminal>("Main_dataBaseModel.FK_Terminals_Brokers", "Terminal");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Terminal>("Main_dataBaseModel.FK_Terminals_Brokers", "Terminal", value);
}
}
}
#endregion
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="Main_dataBaseModel", Name="Client")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Client : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Client object.
/// </summary>
/// <param name="id">Initial value of the ID property.</param>
public static Client CreateClient(global::System.Guid id)
{
Client client = new Client();
client.ID = id;
return client;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Guid ID
{
get
{
return _ID;
}
set
{
if (_ID != value)
{
OnIDChanging(value);
ReportPropertyChanging("ID");
_ID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ID");
OnIDChanged();
}
}
}
private global::System.Guid _ID;
partial void OnIDChanging(global::System.Guid value);
partial void OnIDChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Name
{
get
{
return _Name;
}
set
{
OnNameChanging(value);
ReportPropertyChanging("Name");
_Name = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Name");
OnNameChanged();
}
}
private global::System.String _Name;
partial void OnNameChanging(global::System.String value);
partial void OnNameChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Account
{
get
{
return _Account;
}
set
{
OnAccountChanging(value);
ReportPropertyChanging("Account");
_Account = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Account");
OnAccountChanged();
}
}
private global::System.String _Account;
partial void OnAccountChanging(global::System.String value);
partial void OnAccountChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Comment
{
get
{
return _Comment;
}
set
{
OnCommentChanging(value);
ReportPropertyChanging("Comment");
_Comment = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Comment");
OnCommentChanged();
}
}
private global::System.String _Comment;
partial void OnCommentChanging(global::System.String value);
partial void OnCommentChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Single> Assets
{
get
{
return _Assets;
}
set
{
OnAssetsChanging(value);
ReportPropertyChanging("Assets");
_Assets = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Assets");
OnAssetsChanged();
}
}
private Nullable<global::System.Single> _Assets;
partial void OnAssetsChanging(Nullable<global::System.Single> value);
partial void OnAssetsChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Virtual_Assets
{
get
{
return _Virtual_Assets;
}
set
{
OnVirtual_AssetsChanging(value);
ReportPropertyChanging("Virtual_Assets");
_Virtual_Assets = StructuralObject.SetValidValue(value, true);
ReportPropertyChanged("Virtual_Assets");
OnVirtual_AssetsChanged();
}
}
private global::System.String _Virtual_Assets;
partial void OnVirtual_AssetsChanging(global::System.String value);
partial void OnVirtual_AssetsChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttri
Have you tried?
context.Levels.Add(z);
context.SaveChanges();
If that does not work, wrap an exception handler around the above operations and catch what exceptions are thrown.
So the full code will be:
using(var context = new Main_dataBaseEntities())
{
try
{
var z = new Level {Path = "zPath"};
context.Levels.Add(z);
context.SaveChanges();
}
catch(Exception ex)
{
//View or handle exception here
}
}
You should replace Exception above with a more specific exception in production code but it will suffice here to see what is causing your problem.
The savechanges methode returns the number of objects in an Added, Modified, or Deleted state, try to debug and see what you get as a return value and if any exceptions are thrown. Personally i prefer the Database first approach.
int num = context.SaveChanges();