I have a web application where i want my users to dynamically cre开发者_如何学JAVAate a type...i can do this using reflection but i am not sure of how to persist that type using Entity framework
Once again - whether this approach is applicable or not (and in any case it is a workaround), depends on your scenario. However, what you can do is serialize your object and store it in a database field. You can basically serialize into any format (binary, json, xml, ...).
Note: when using the xml
datatype you can actually query for the data inside the object (not sure if you can do that directly with EF, but you can always write an SP and call it with EF). See this link for an example.
Here is an overview of Storing serialized objects in SQL Server.
Here is an implementation of an XML serializer. You can use it to serialize your object into a string before assigning it to your entities property.
You can't do this because entity framework will not have mapping metadata for dynamically created type, context will not have ObjectSet
for new entity and database will not have table for your new type.
Central storage of metadata for EF is MetadataWorkspace class but in current version of EF this class is not supposed to be modified at runtime. It doesn't offer any methods to do that. The only way to define MetadataWorkspace at runtime is from modified SSDL (database description), MSL (mapping description) and CSDL (entity classes description) files. So any "dynamic" approach to EF means:
- create types at runtime (reflection.emit)
- create derived
ObjectContext
containing newObjectSet
at runtime (reflection.emit) - modify database to contain new tables
- create all these mapping files at runtime
- load mapping files at runtime, create new
EntityConnection
with createdMetadataWorkspace
and pass it to instance of dynamically createdObjectContext
derived type - write a code which is able to work with dynamically created entities
- write some code which is able to persist information about new entity types and new object context because otherwise you will not have these types available after restarting application
Edit:
You can also use workaround as mentioned by @Yakimych. Serialize instance of your dynamic type and save it as varbinary (binary serialization) or varchar (xml serialization). You will need only simple table with Id (PK) and column for serialized data. You will query table by Id and handle deserialization by yourselves. You will not be able to query table by type specific properties.
精彩评论