Entity context does not update database - c#
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();
Related
Update Statement Local Database using Linq
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
Silverlight talking to a WCF using RIA Services Silverlight Client
My silverlight project has references to the RIA Services Silverlight Client and my .web application has access to RIAServices.Server. I can't seem to find a good tutorial to learn how to connect these. Once I understand how to get the data from my NumberGenerator method. I can pick it up from there. I have three questions that I need some help with. First, am I setting up this project correctly? I never done a project with RIA before. Secondly what reference do I need to use ServiceContract(), FaultContract, and OperationContract? Most examples show that they are in the System.ServiceModel library. In this case with using the external library RIA Services Silverlight Client that is not the case. It throws a error saying I am missing a reference. What other libraries would have those three in it? My last question is what URI do you use in the SystemDomainContext? Where I found the code at used this MyFirstRIAApplication-Web-EmployeeDomainService.svc but in my case I don't have anything that has a .svc extension. Would I use the .xap or .aspx? Here is my Silverlight code Here is my NumberGenerator Silverlight UserControl Page Code public partial class NumberGenerator : UserControl { public NumberGenerator() { InitializeComponent(); GenerateNumber(); } private void GenerateButton_Click(object sender, RoutedEventArgs e) { GenerateNumber(); } private void GenerateNumber() { int result = 0 SystemClientServices systemclientservices = SystemClientServices.Instance; result = systemclientservices.GenerateNumber(); NumberLabel.Content = result; } } Here is my System Client Services class private readonly static SystemClientServices _instance = new SystemClientServices(); private SystemDomainContext _domainContext = new SystemDomainContext(); private SystemClientServices() { } public static SystemClientServices Instance { get { return _instance; } } public int GenerateNumber() { //Code goes here to get the information from the Domainservices LoadOperation load = this._domainContext.Load(this._domainContext.GetNumberGeneratorQuery(), LoadBehavior.KeepCurrent, false); return Convert.ToInt32(load.Entities); } Here is my NumberGenerator class on the silverlight local project public sealed partial class NumberGenerator : Entity { private static readonly NumberGenerator _instance = new NumberGenerator(); public int NumberGenerated { get; set; } public NumberGenerator() { NumberGenerated = 0; } public static NumberGenerator Instance { get { return _instance; } } } Here is System Domain Conext class on the silverlight local project using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel.DomainServices; using System.ServiceModel.DomainServices.Client; using System.ServiceModel.DomainServices.Client.ApplicationServices; using System.ServiceModel.Web; using System.ServiceModel; public sealed partial class SystemDomainConext : DomainContext { #region Extensibility Method Definitions /// <summary> /// This method is invoked from the constructor once initialization is complete and /// can be used for further object setup. /// </summary> partial void OnCreated(); #endregion /// <summary> /// Initializes a new instance of the <see cref="EmployeeDomainContext"/> class. /// </summary> public SystemDomainConext() : this(new WebDomainClient<ISystemDomainServiceContract>(new Uri("MyFirstRIAApplication-Web-EmployeeDomainService.svc", UriKind.Relative))) { } /// <summary> /// Initializes a new instance of the <see cref="EmployeeDomainContext"/> class with the specified service URI. /// </summary> /// <param name="serviceUri">The EmployeeDomainService service URI.</param> public SystemDomainConext(Uri serviceUri) : this(new WebDomainClient<ISystemDomainServiceContract>(serviceUri)) { } /// <summary> /// Initializes a new instance of the <see cref="EmployeeDomainContext"/> class with the specified <paramref name="domainClient"/>. /// </summary> /// <param name="domainClient">The DomainClient instance to use for this DomainContext.</param> public SystemDomainConext(DomainClient domainClient) : base(domainClient) { this.OnCreated(); } /// <summary> /// Gets the set of <see cref="Employee"/> entity instances that have been loaded into this <see cref="EmployeeDomainContext"/> instance. /// </summary> public EntitySet<NumberGenerator> GeneratedNumber { get { return base.EntityContainer.GetEntitySet<NumberGenerator>(); } } /// <summary> /// Gets an EntityQuery instance that can be used to load <see cref="Employee"/> entity instances using the 'GetEmployee' query. /// </summary> /// <returns>An EntityQuery that can be loaded to retrieve <see cref="Employee"/> entity instances.</returns> public EntityQuery<NumberGenerator> GetNumberGeneratorQuery() { this.ValidateMethod("GetGeneratedNumber", null); return base.CreateQuery<NumberGenerator>("GetNumberGenerator", null, false, true); } /// <summary> /// Creates a new EntityContainer for this DomainContext's EntitySets. /// </summary> /// <returns>A new container instance.</returns> protected override EntityContainer CreateEntityContainer() { return new NumberGeneratorDomainContextEntityContainer(); } /// <summary> /// Service contract for the 'EmployeeDomainService' DomainService. /// </summary> [ServiceContract()] public interface ISystemDomainServiceContract { /// <summary> /// Asynchronously invokes the 'GetEmployee' operation. /// </summary> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [FaultContract(typeof(DomainServiceFault), Action="http://tempuri.org/EmployeeDomainService/GetEmployeeDomainServiceFault", Name="DomainServiceFault", Namespace="DomainServices")] [OperationContract(AsyncPattern=true, Action="http://tempuri.org/EmployeeDomainService/GetEmployee", ReplyAction="http://tempuri.org/EmployeeDomainService/GetEmployeeResponse")] [WebGet()] IAsyncResult GetGeneratedNumber(AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginGetEmployee'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginGetEmployee'.</param> /// <returns>The 'QueryResult' returned from the 'GetEmployee' operation.</returns> QueryResult<NumberGenerator> EndGetGeneratedNumber(IAsyncResult result); /// <summary> /// Asynchronously invokes the 'SubmitChanges' operation. /// </summary> /// <param name="changeSet">The change-set to submit.</param> /// <param name="callback">Callback to invoke on completion.</param> /// <param name="asyncState">Optional state object.</param> /// <returns>An IAsyncResult that can be used to monitor the request.</returns> [FaultContract(typeof(DomainServiceFault), Action="http://tempuri.org/EmployeeDomainService/SubmitChangesDomainServiceFault", Name="DomainServiceFault", Namespace="DomainServices")] [OperationContract(AsyncPattern=true, Action="http://tempuri.org/EmployeeDomainService/SubmitChanges", ReplyAction="http://tempuri.org/EmployeeDomainService/SubmitChangesResponse")] IAsyncResult BeginSubmitChanges(IEnumerable<ChangeSetEntry> changeSet, AsyncCallback callback, object asyncState); /// <summary> /// Completes the asynchronous operation begun by 'BeginSubmitChanges'. /// </summary> /// <param name="result">The IAsyncResult returned from 'BeginSubmitChanges'.</param> /// <returns>The collection of change-set entry elements returned from 'SubmitChanges'.</returns> IEnumerable<ChangeSetEntry> EndSubmitChanges(IAsyncResult result); } internal sealed class NumberGeneratorDomainContextEntityContainer : EntityContainer { public NumberGeneratorDomainContextEntityContainer() { this.CreateEntitySet<NumberGenerator>(EntitySetOperations.Edit); } } } Here is my System Domain Services class that is on the Silverlight.web [EnableClientAccess()] public class SystemDomainServices : DomainService { private NumberGenerator numberGenerator = NumberGenerator.Instance; public int NumberGenerate() { return numberGenerator.NumberGenerated; } } Here is the NumberGenerator class on the silverlight.web private static readonly NumberGenerator _instance = new NumberGenerator(); [Key] public int NumberGenerated { get; set; } public NumberGenerator() { NumberGenerated = GenerateNumber(); } public static NumberGenerator Instance { get { return _instance; } } public int GenerateNumber() { string db_date = ""; int db_num = 0; string todaysdate = ""; int temp_num = db_num; int result = 0; using (SqlConnection connection = new SqlConnection(DBConnectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * FROM table", connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { db_date = reader.GetString(0); db_num = (int)(reader.GetSqlInt32(1)); todaysdate = DateTime.Now.ToString("yMMdd"); temp_num = db_num; } reader.Close(); } if (todaysdate != db_date) { using (SqlCommand dateUpate = new SqlCommand("UPDATE table SET tsDate='" + todaysdate + "' WHERE tsDate='" + db_date + "'", connection)) { dateUpate.ExecuteNonQuery(); } db_num = 0; db_date = todaysdate; } db_num++; using (SqlCommand numUpate = new SqlCommand("UPDATE table SET tsNum='" + db_num + "' WHERE tsNum='" + temp_num + "'", connection)) { numUpate.ExecuteNonQuery(); } result = Convert.ToInt32(db_date + db_num.ToString().PadLeft(3, '0')); connection.Close(); connection.Dispose(); } return result; } }
The answer to question two you might be have to go to Tools at the top, NuGet Package Manager, Package Management Console, and then type the following command to install the package for those three functions. PM> Install-Package RIAServices.Silverlight.DomainDataSource
Get the exact type as property in C# class
Sorry for the general title but it's a bit hard to explain in few words what is my problem currently. So I have a simple class factory like this: public Model Construct<T>(T param) where T : IModelable { new Model {Resource = param}; return n; } The Model class looks like this: public class Model { public object Resource { get; set; } } The problem is, that you can see, is the Resource is currently an object. And I would like that Resource should be the type, what is get from the Construct and not lost the type-safe... I tried to solve it with type parameter but it fails, because I can extend Model class with type parameter but what if I would like to store it to a simple class repository? Then Construct will work, but if I would like to get the instanced class from the repository, I have to declare the type paramter again like: Repository.Get<Model<Spaceship>>(0) .... and of course it's wrong because I would like that Model itself knows, what type of Resource has been added in Construct. Does anybody any idea how to handle this? The whole code currently look like this: /// <summary> /// Class Repository /// </summary> public sealed class Repository { /// <summary> /// The _lock /// </summary> private static readonly object _lock = new object(); /// <summary> /// The _syncroot /// </summary> private static readonly object _syncroot = new object(); /// <summary> /// The _instance /// </summary> private static volatile Repository _instance; /// <summary> /// The _dict /// </summary> private static readonly Dictionary<int, object> _dict = new Dictionary<int, object>(); /// <summary> /// Prevents a default data of the <see cref="Repository" /> class from being created. /// </summary> private Repository() { } /// <summary> /// Gets the items. /// </summary> /// <value>The items.</value> public static Repository Data { get { if (_instance == null) { lock (_lock) { if (_instance == null) _instance = new Repository(); } } return _instance; } } /// <summary> /// Allocates the specified id. /// </summary> /// <param name="id">The id.</param> /// <param name="parameter">The parameter.</param> /// <resource name="id">The id.</resource> /// <resource name="parameter">The parameter.</resource> public void Allocate(int id, object parameter) { lock (_syncroot) { _dict.Add(id, parameter); } } /// <summary> /// Gets the specified id. /// </summary> /// <typeparam name="T">The type of the tref.</typeparam> /// <param name="id">The id.</param> /// <returns>``0.</returns> /// <resource name="id">The id.</resource> public T Get<T>(int id) { lock (_syncroot) { return (T) _dict[id]; } } } /// <summary> /// Class IModelFactory /// </summary> public sealed class ModelFactory { /// <summary> /// The _lock /// </summary> private static readonly object _lock = new object(); /// <summary> /// The _instance /// </summary> private static volatile ModelFactory _instance; /// <summary> /// Prevents a default instance of the <see cref="ModelFactory" /> class from being created. /// </summary> private ModelFactory() { } /// <summary> /// Gets the data. /// </summary> /// <value>The data.</value> public static ModelFactory Data { get { if (_instance == null) { lock (_lock) { if (_instance == null) _instance = new ModelFactory(); } } return _instance; } } /// <summary> /// Constructs the specified param. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="param">The param.</param> /// <returns>Model{``0}.</returns> public Model Construct<T>(T param) where T : IModelable { var n = new Model {Resource = param}; return n; } } /// <summary> /// Class Model /// </summary> /// <typeparam name="T"></typeparam> public class Model { public object Resource { get; set; } } /// <summary> /// Interface IModelable /// </summary> public interface IModelable { /// <summary> /// Gets or sets the mass. /// </summary> /// <value>The mass.</value> float Mass { get; set; } } /// <summary> /// Class spaceship /// </summary> public class Spaceship : IModelable { /// <summary> /// Gets or sets the mass. /// </summary> /// <value>The mass.</value> public float Mass { get; set; } } So the problem will be lighted here: Add to the Repository: Repository.Data.Allocate(1, ModelFactory.Data.Construct(new Spaceship())); It's okay, but after: var test_variable = Repository.Data.Get<Model>(1); So now I have a non type-safe object from a type parameter, I don't know, that what type of class has been stored with the c model construction. I'm very thankful for the suggestions of using type paramter on the Model class as well, but than it will come up another problem, because I have to change the Get function with it: var test_variable = Repository.Data.Get<Model<Spaceship>>(1); But that's definitely wrong, because I won't know, that what kind of type of class has been stored in the model..., so I would like to achieve to avoid this type parameter definition when I would like to load the instance from the Repository.
You can solve this by making your Model class generic, like this: public class Model<T> { public T Resource { get; set; } } Then, your Construct method could work like this: public Model<T> Construct<T>(T param) where T : IModelable<T> { return new Model<T>() {Resource = param}; }
You probably need a generic type in the model class: public class Model<T> { public T Resource { get; set; } }
This sort of structure is one approach you could take: public Model<T> Construct<T>(T param) where T : IModelable { var n = new Model<T> {Resource = param}; return n; } public class Model<T> : IModel<T> where T : IModelable { public T Resource { get; set; } } public interface IModel<out T> where T : IModelable { T Resource { get; } } This covariant interface allows you to refer to the types more generically where you wish, in the same way that you can pass an IEnumerable<string> into something expecting an IEnumerable<object>. IModel<Spaceship> shipModel = // whatever IModel<IModelable> model = shipModel; //or even: List<Model<Spaceship>> shipModels = // whatever IEnumerable<IModel<IModelable>> models = shipModels;
Include not working with Entity Framework query
I'm not sure what changed, but, after coming back to an application I was working on a few weeks ago, my .Include() call is no longer working for for one of my related tables. The weird part is that it works for a different table. Here is some code with comments showing what my results are: //Get the order and nothing else. using (OrderEntity orderContext = new OrderEntity(OrdersConnectionString)) { var query = from order in orderContext.ShippingOrders where order.ShipperId == shippingId select order; //I got a value! shippingOrder = query.ToList().FirstOrDefault(); } //Get the line item and nothing else. using (OrderEntity orderContext = new OrderEntity(OrdersConnectionString)) { var query = from orderItem in orderContext.ShippingOrderItems where orderItem.ShipperId == shippingId select orderItem; //I got a value! shippingOrderItems = query.ToList(); } Here is where I am confused: //Get the order *AND* the line item using (OrderEntity orderContext = new OrderEntity(OrdersConnectionString)) { var query = from order in orderContext.ShippingOrders.Include("ShippingOrderItems") where order.ShipperId == shippingId select order; //I get a ShippingOrder result, but no items are returned. I used the SQL Server Profiler and saw the SQL that got executed; it contains the item, EF just isn't loading the object. shippingOrder = query.ToList().FirstOrDefault(); } I am able to get back results for a different related table. This makes me think that the EF is missing the relationship between my order and line item table, but, I'm not sure how I can fix that. Edit: Here is the Order Entity /// <summary> /// No Metadata Documentation available. /// </summary> [EdmEntityTypeAttribute(NamespaceName="OrderModel", Name="ShippingOrder")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class ShippingOrder : EntityObject { #region Factory Method /// <summary> /// Create a new ShippingOrder object. /// </summary> /// <param name="shipperId">Initial value of the ShipperId property.</param> public static ShippingOrder CreateShippingOrder(global::System.String shipperId) { ShippingOrder shippingOrder = new ShippingOrder(); shippingOrder.ShipperId = shipperId; return shippingOrder; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.String ShipperId { get { return _ShipperId; } set { if (_ShipperId != value) { OnShipperIdChanging(value); ReportPropertyChanging("ShipperId"); _ShipperId = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("ShipperId"); OnShipperIdChanged(); } } } private global::System.String _ShipperId; partial void OnShipperIdChanging(global::System.String value); partial void OnShipperIdChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String OrderNumber { get { return _OrderNumber; } set { OnOrderNumberChanging(value); ReportPropertyChanging("OrderNumber"); _OrderNumber = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("OrderNumber"); OnOrderNumberChanged(); } } private global::System.String _OrderNumber; partial void OnOrderNumberChanging(global::System.String value); partial void OnOrderNumberChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable<global::System.DateTime> OrderDate { get { return _OrderDate; } set { OnOrderDateChanging(value); ReportPropertyChanging("OrderDate"); _OrderDate = StructuralObject.SetValidValue(value); ReportPropertyChanged("OrderDate"); OnOrderDateChanged(); } } private Nullable<global::System.DateTime> _OrderDate; partial void OnOrderDateChanging(Nullable<global::System.DateTime> value); partial void OnOrderDateChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String CustomsComment { get { return _CustomsComment; } set { OnCustomsCommentChanging(value); ReportPropertyChanging("CustomsComment"); _CustomsComment = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("CustomsComment"); OnCustomsCommentChanged(); } } private global::System.String _CustomsComment; partial void OnCustomsCommentChanging(global::System.String value); partial void OnCustomsCommentChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("OrderModel", "FK_ShippingOrderItem_ShippingOrder", "ShippingOrderItem")] public EntityCollection<ShippingOrderItem> ShippingOrderItems { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ShippingOrderItem>("OrderModel.FK_ShippingOrderItem_ShippingOrder", "ShippingOrderItem"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ShippingOrderItem>("OrderModel.FK_ShippingOrderItem_ShippingOrder", "ShippingOrderItem", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("OrderModel", "FK_ShippingOrderItemTracking_ShippingOrder", "ShippingOrderTracking")] public EntityCollection<ShippingOrderTracking> ShippingOrderTrackings { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ShippingOrderTracking>("OrderModel.FK_ShippingOrderItemTracking_ShippingOrder", "ShippingOrderTracking"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ShippingOrderTracking>("OrderModel.FK_ShippingOrderItemTracking_ShippingOrder", "ShippingOrderTracking", value); } } } #endregion }
I'm still not sure what the cause of the issue was. I decided to just drop my database and re-create my tables (along with the primary and foreign keys) and migrate over all the data again. It actually fixed it, but, I'm not sure what ended up being different. I was not getting any exceptions logged and based on the SQL Server Profiler it looked like the correct query was being executed.
You can also try this: if (Order.shippingId != null && Order.shippingId > 0) orderContext.LoadProperty(Orders, Order => Order.ShippingOrderItems); This will fetch the matching order id in ShippingOrderItems.
.NET 4.0 application to use Microsoft ADO Ext. 6.0 for DDL and Security
I try to compile Xsd2Db solution in .NET 4.0 framework. I add a reference to "Microsoft ADO Ext. 6.0 for DDL and Security" and use it in this way - using System; using System.IO; using ADOX; namespace Xsd2Db.Data { /// <summary> /// Summary description for JetDataSchemaAdapter. /// </summary> public sealed class JetDataSchemaAdapter : AdoxDataSchemaAdapter { /// <summary> /// /// </summary> internal const string Extension = ".mdb"; /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> internal static string GetPath(string name) { return Path.GetFullPath( Path.ChangeExtension(name, Extension)); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> internal static string GetConnectionString(string name) { return String.Format( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5;", GetPath(name)); } /// <summary> /// /// </summary> /// <param name="name"></param> protected override void DeleteCatalog(string name) { File.Delete(GetPath(name)); } /// <summary> /// /// </summary> /// <param name="name"></param> protected override void CreateCatalog(string name) { // Force the run-time to let go of the file! Otherwise, // cleanup and other operations might fail because the file // will still be in use. Catalog catalog = new CatalogClass(); catalog.Create(GetConnectionString(name)); catalog.ActiveConnection = null; catalog = null; GC.Collect(); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> protected override Catalog OpenCatalog(string name) { Catalog catalog = new CatalogClass(); catalog.let_ActiveConnection(GetConnectionString(name)); return catalog; } } } Now I have an error during compiling -- "The type 'ADOX.CatalogClass' has no constructors defined". Clicking the error link brings me to the meta data - #region Assembly Interop.ADOX.dll, v4.0.30319 // C:\xsd\xsd2db\xsd2db\Common\DataSchemaAdapter\obj\Debug\Interop.ADOX.dll #endregion using System; using System.Reflection; using System.Runtime.InteropServices; namespace ADOX { [Guid("00000602-0000-0010-8000-00AA006D2EA4")] [ClassInterface(0)] [TypeLibType(2)] public class CatalogClass : _Catalog, Catalog { public CatalogClass(); [DispId(1)] public virtual dynamic ActiveConnection { get; set; } [DispId(4)] public virtual Groups Groups { get; } [DispId(2)] public virtual Procedures Procedures { get; } [DispId(0)] public virtual Tables Tables { get; } [DispId(5)] public virtual Users Users { get; } [DispId(3)] public virtual Views Views { get; } [DispId(6)] public virtual dynamic Create(string ConnectString); [DispId(7)] public virtual string GetObjectOwner(string ObjectName, ObjectTypeEnum ObjectType, object ObjectTypeId = Type.Missing); [DispId(1)] public virtual void let_ActiveConnection(object pVal); [DispId(8)] public virtual void SetObjectOwner(string ObjectName, ObjectTypeEnum ObjectType, string UserName, object ObjectTypeId = Type.Missing); } } We can see public CatalogClass(); but not a constructor. I believe in .NET 1.x this worked. But why .NET 4.0 has this problem? Anyone encoutered this and What is the best way to handle this? Thanks!
I did a search and found out the problem does exist in .NET 4.0. Here are some explanations and solutions - http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx; http://mokosh.co.uk/post/2010/04/10/net-4-0-interop-type-cannot-be-embedded-use-the-applicable-interface-instead/