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;
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.
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();
I have a class
public class Setting<T>
{
public string name { get; set; }
public T value { get; set; }
}
now I want to create an IList<Setting<T>> but with different types of Setting<T>'s T in it, I want e.G.
List<Setting<T>> settingsList;
settingsList.Add(new Setting<int>());
settingsList.Add(new Setting<string>());
I've tried IList<Setting<T>> but this seems not possible since the compiler doesn't find Type T.
I know that I could use object but I want it to be strongly typed. So my question is if there is a possibility of getting this working.
Generic types do not have a common type or interface amongst concrete definitions by default.
Have your Setting<T> class implement an interface (or derive from a common class) and create a list of that interface (or class).
public interface ISetting { }
public class Setting<T> : ISetting
{
// ...
}
// example usage:
IList<ISetting> list = new List<ISetting>
{
new Setting<int> { name = "foo", value = 2 },
new Setting<string> { name = "bar", value "baz" },
};
You have to use a common ancestor class for all the class types that you put into the list. If it should be arbitrary types you have to use object for T
You can use T only inside your class:
class Setting<T>
{
// T is defined here
}
not outside. Outside you need to specify the concrete type:
Settings<string> stringSettings = new Settings<string>();
or
List<Settings<string>> list = new List<Settings<string>>();
list.Add(stringSettings);
ye you can do it by using reflection
i wrote such code for another question but you can use this
public abstract class GenericAccess
{
public static IList<T> GetObjectListFromArray<T>(T item)
{
var r = new List<T>();
var obj = typeof(T).Assembly.CreateInstance(typeof(T).FullName);
var p = obj.GetType().GetProperty("Id", System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
if (p != null)
{
p.SetValue(obj, item, null);
var m = r.GetType().GetMethod("Add");
m.Invoke(r, new object[] { obj });
}
return r;
}
}
and call it like this
IList<int> r = GenericAccess.GetObjectListFromArray<int>(1);
/// <summary>
/// 消息回调委托
/// </summary>
/// <typeparam name="T">TClass</typeparam>
/// <param name="result">返回实体</param>
/// <param name="args">内容包</param>
public delegate void CallbackHandler<in T>(T result, BasicDeliverEventArgs args);
/// <summary>
/// 注册监听程序接口
/// </summary>
public interface IRegistration
{
/// <summary>
/// 路由名称
/// </summary>
string ExchangeName { get; }
/// <summary>
/// 路由Key
/// </summary>
string RouteKey { get; }
/// <summary>
/// 回调操作
/// </summary>
/// <param name="args"></param>
void Call(BasicDeliverEventArgs args);
}
/// <summary>
/// 注册监听程序
/// </summary>
/// <typeparam name="T"></typeparam>
public class Registration<T> : IRegistration where T : class
{
/// <summary>
/// 路由名称
/// </summary>
public string ExchangeName { get; set; }
/// <summary>
/// 路由Key
/// </summary>
public string RouteKey { get; set; }
/// <summary>
/// 消息处理器委托
/// </summary>
public CallbackHandler<T> Handler { get; set; }
/// <summary>
/// 接口回调操作
/// </summary>
/// <param name="args"></param>
public void Call(BasicDeliverEventArgs args)
{
var message = Encoding.UTF8.GetString(args.Body.ToArray());
Handler?.Invoke(JsonConvertHandler.DeserializeObject<T>(message), args);
}
}
/// <summary>
/// 消息监听处理器
/// </summary>
public static class ListenerHandler
{
/// <summary>
/// 单任务锁
/// </summary>
private static readonly object Locker = new object();
/// <summary>
/// 所有注册列表
/// </summary>
public static List<IRegistration> Registrations { get; private set; }
/// <summary>
/// 单例化
/// </summary>
static ListenerHandler()
{
List<ListenerSetting> listeners = MqNoticeHandler.Setting.GetListeners();
MqNoticeHandler.Listener(OnMessage, listeners);
}
/// <summary>
/// 注册监听
/// </summary>
/// <param name="registration"></param>
public static void Register(IRegistration registration)
{
lock (Locker)
Registrations.Add(registration);
}
/// <summary>
/// 解除注册
/// </summary>
/// <param name="registration"></param>
public static void UnRegister(IRegistration registration)
{
lock (Locker)
Registrations.Remove(registration);
}
/// <summary>
/// 获取监听列表
/// </summary>
/// <param name="exchangeName"></param>
/// <param name="routeKey"></param>
/// <returns></returns>
public static IEnumerable<IRegistration> GetRegistrations(string exchangeName, string routeKey)
{
return Registrations.Where(x => x.ExchangeName == exchangeName && x.RouteKey == routeKey);
}
/// <summary>
/// 消息回调处理
/// </summary>
/// <param name="consumer">消费者</param>
/// <param name="args">消息包</param>
/// <returns></returns>
private static MqAckResult OnMessage(EventingBasicConsumer consumer, BasicDeliverEventArgs args)
{
//Example Query and Call
Registrations.First().Call(args);
//Return
return new MqAckResult { Accept = true, ReQueue = false };
}
}
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/