If you do not want to use the Visual Studio designer to generate your Entity Framework schema files you can use
edmgen instead. I spent some time poking around this application in Reflector and found out what’s involved. You can use this code to generate the Entity Framework schema files directly yourself.
Note: You will first need to reference the "System.Data.Entity.Design" assembly and namespace.
Generating the SSDL file:
const string Provider = "System.Data.SqlClient";
const string ConnectionString = "server=.;database=MyDatabase;integrated security=true;";
const string Namespace = "Testing";
var generator = new EntityStoreSchemaGenerator(Provider, ConnectionString, Namespace);
generator.GenerateStoreMetadata();
generator.WriteStoreSchema(@"D:\temp\storeSchema.ssdl");
var storeEntityContainer = generator.EntityContainer;
Generating the CSDL and MSL files:
const string Namespace = "Testing";
const string ContainerName = "MyContainer";
EntityModelSchemaGenerator generator = new EntityModelSchemaGenerator(storeEntityContainer, Namespace, ContainerName);
generator.GenerateMetadata();
generator.WriteModelSchema(@"D:\temp\modelSchema.csdl");
generator.WriteStorageMapping(@"D:\temp\storageMapping.msl");
Generate Classes:
private static void GenerateObjectLayerCode(string csdlFile, IEnumerable additionalSchemas)
{
var generator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode);
var reader = XmlReader.Create(csdlFile);
var writer = new StringWriter();
generator.GenerateCode(reader, writer, additionalSchemas);
string code = writer.GetStringBuilder().ToString();
}
The disappointment is that the extensibility for generating the classes in the last step is extremely limited. You only have two options – implement event handlers that fire when a Type and/or Property is created. The problem is that the TypeGeneratedEventArgs and PropertyGeneratedEventArgs classes passed to your event handler are extremely limited. For the properties you are not passed the entire CodeDOM CodeMemberProperty instance. Instead you are only allowed to add additional get/set statements. You have no way of completely customizing the property definition. In a future post I plan to explore the usage of NRefactory to accomplish this.