Assign value from sql query to a field in CRM using C# - c#

Im trying to create a plugin for CRM that queries a mysql db and pulls the data from the db and adds it to a field in crm. What i have so far is this below, but im not sure how to assign a table column to a field value in crm?
`namespace Microsoft.Crm.Sdk.Samples
{
public class AssignSMSPlugin: IPlugin
{
/// <summary>
/// A plug-in that creates a follow-up task activity when a new account is created.
/// </summary>
/// <remarks>Register this plug-in on the Create message, account entity,
/// and asynchronous mode.
/// </remarks>
public void Execute(IServiceProvider serviceProvider)
{
//Conect to mySQl Database
String str ="";
MySqlConnection con = null;
MySqlDataReader reader = null;
try
{
con = new MySqlConnection(str);
con.Open();
//Select statement to query table to get certain columns
string cmdText = "SELECT col1, col2, col3 FROM table1";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
reader = cmd.ExecuteReader();
// while (reader.Read())
// {
// Console.WriteLine(reader.GetString(0));
// }
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "customer")
return;
try
{
// Create a sms activity.Assign table column to field in crm
Entity assign = new Entity("SMS Message");
assign["to"] = "";
assign["subject"] = "";
assign["contact"] = ;
assign["regardingobjectid"] = ;
// Refer to the account in the task activity.
if (context.OutputParameters.Contains("id"))
{
Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
string regardingobjectidType = "customer";
assign["regardingobjectid"] =
new EntityReference(regardingobjectidType, regardingobjectid);
}
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
// Create the task in Microsoft Dynamics CRM.
tracingService.Trace("AssignSMSPlugin: Creating the SMS Activity.");
service.Create(assign);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the AssignSMSPlugin plug-in.", ex);
}
catch (Exception ex)
{
tracingService.Trace("AssignSMSPlugin: {0}", ex.ToString());
throw;
}
}
}
}`

Your logic looks faulty to me.
1) Change the part here
assign["to"] = "";
assign["subject"] = "";
assign["contact"] = ;
assign["regardingobjectid"] = ;
you need to actually assign values instead of nulls/empty strings.
2) There is generally some type of primary field (usually name/subject/title) on any entity; that should be set (I assume that is the subject field, which is currently = "") or it will come back to bite you.
3) you probably should use Entity.Attributes.Contains("id") instead of "OutputParameters" for context.OutputParameters.Contains("id") as I doubt you registered the plugin to have output parameters (this would require you to be generating them from a separate plugin)
4) I don't know about accessing MySQL via C#, but I assume you need to get the data from MySQL from that "reader", and use that to populate the CRM Values.
5) in most CRM plugins, the Org Service and ServiceFactory are instantiated at the beginning along with the tracing, so I would recommend moving that up much higher (this one is more of improved readability, so you can skip it).
6) your comments keep referring to accounts, but the check at the beginning is for "customer" (again, optional as it is just poor commenting)
7) the assign "Entity" is not a valid entity name, there should not be any spaces - more likely the entity name is something like
var assign = new Entity("new_smsmessage")

Related

How to insert the value of custom field while creating the entity record?

I'm facing a problem about how to insert the custom field value through create a new systemuser.
In Microsoft CRM system, there has systemuser table and I have a custom field named "SSOID", and the value of "SSOID" I get it from webapi.
My requirement is when I am in systemuser creation page in CRM, I enter the domainname value to the domainname textbox, the other fields like firstname, lastname and businessID will auto populated base on domainname. They come from active directory.
And meanwhile I also call the webapi to get the SSOID base on domainname.
What I want is after I click the save button, the new systemuser should be create and the SSOID also should be insert along with new systemuser.
But now when I click the button, some error happened
usersettings With Id = 5ab7eb74-511a-ea11-810b-005056ba5450 Does Not Exist
Below is my code, it looks very simple, but some error happened;
IPluginExecutionContext context;
IOrganizationServiceFactory factory;
IOrganizationService service;
// 获取执行上下文
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// 获取服务工厂
factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
// 获取服务
service = factory.CreateOrganizationService(context.UserId);
if (context.MessageName.ToLower() == "create"
&& context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
try
{
var domainName = "";
Entity entity = (Entity)context.InputParameters["Target"];
if (context.Depth > 1)
{ return; }
if (entity.Attributes.Contains("domainname"))
{
domainName = entity["domainname"].ToString();
}
var SSOId = " get from webapi";
if (!string.IsNullOrEmpty(SSOId))
{
var businessEntityRef = (Microsoft.Xrm.Sdk.EntityReference)(entity.Attributes["businessunitid"]);
var businessunit = service.Retrieve(businessEntityRef.LogicalName, businessEntityRef.Id, new ColumnSet(true));
entity["businessunitid"] = businessEntityRef; // businessunit id is look up field comes from businessunit reference table
entity["domainname"] = entity["domainname"];
entity["lastname"] = entity["lastname"];
entity["firstname"] = entity["firstname"];
entity["new_ssoid"] = SSOId;
service.Update(entity); //i can't use create method, it shows "The specified Active Directory user already exists as a Dynamics 365 user"
}
else
{
throw new InvalidPluginExecutionException("userID not exist");
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
I'm new to CRM plugin development, can anyone who guide me how to solve this problem?
Please use the below code:
var SSOId = " get from webapi";
if (!string.IsNullOrEmpty(SSOId))
{
Entity entityToUpdate = new Entity("systemuser", new Guid(entity.Id));
entityToUpdate["new_ssoid"] = SSOId;
service.Update(entityToUpdate);
}
else
{
throw new InvalidPluginExecutionException("userID not exist");
}
You need to create a new instance of entity object to update after record creation (Post-create Asynchronous plugin).
Also if you throw exception when there is no error, the transaction will rollback. Think about it.

Change DBase On Run Time C# app

I have developed an accounting program that is working beautifully, but now a new need has arisen.
When I enter the program, by default it reads the DB that I put in the file WinSCM.exe.config and if I want to change I have to exit the program and edit the file changing the DB name.
I did not want it to be this way, because my client does accounting for several companies and each company is a DB, so I wanted a way to select a company and when selecting this company the database is automatically changed in the release version.
I'm using Entity Framework to connect to Sql Server DB
Can someone help me?
I'm not sure what reading your DB is, but normally when you use Entity Framework you create a DbContext object whenever you need to do a query, or at utmost a few queries. You are not supposed to keep this DbContext alive for longer periods of time, say more than a few seconds. A minute would be very rare.
Whenever you create the Dbcontext instance you could use the default constructor that uses the config file to get the connection string to the database.
However one of the other constructors let you define the connection string to the database in the constructor. So if you want to construct your DbContext and connect it to a different database, just use that constructor
If you don't know the connection string, but you have a DbConnection to the database, there will be even a constructor for this case.
Hi Everybody Thank alot for your Answer. I just Solved My Question like this:
Fisrt of all, I created a class wich I called ConnetionTolls with this Content://.
public static class ConnectionTools
{
// all params are optional
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
********the way to use it is like this***************
//I use this method in a diferent Class
//This method returns the Entity i use with new connections
public static MyEntities SelectDb(String DataBase,String sqlUser,String pw, String serverInstance){
var selectedDbase = new MyEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDbase.ChangeDatabase
(
initialCatalog: DataBase,
userId: sqlUser,
password: pw,
dataSource: serverInstance// could be ip address 100.23.45.67 etc
);
return selectedDbase;
}
I want to thank everyone here and on other forums because this was the result of Your Contributions

How to add a sql database to an elastic pool programmatically?

I have the following console application which creates a ShardManagerDB and creates one database for each company on the main database.
I can see on azure the databases created on the server however they are not on the elastic pool.
Question:
1. Is this doable with the current API?
2. If not, what are other recommended approaches?
using System.Data.SqlClient;
using mynm.Data;
using System.Linq;
using mynm.Models.GlobalAdmin;
namespace mynm.DbManagementTool
{
class Program
{
static void Main(string[] args)
{
SetupSSM();
}
//This will create the Shard Management DB if it doesnt exist
private static void SetupSSM()
{
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder
{
UserID = SettingsHelper.AzureUsernamedb,
Password = SettingsHelper.AzurePasswordDb,
ApplicationName = SettingsHelper.AzureApplicationName,
DataSource = SettingsHelper.AzureSqlServer
};
DbUtils.CreateDatabaseIfNotExists(connStrBldr.ConnectionString, SettingsHelper.Azureshardmapmgrdb);
Sharding sharding = new Sharding(SettingsHelper.AzureSqlServer, SettingsHelper.Azureshardmapmgrdb, connStrBldr.ConnectionString);
CreateShardPerCompany(sharding);
}
private static void CreateShardPerCompany(Sharding sharding)
{
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder
{
UserID = SettingsHelper.AzureUsernamedb,
Password = SettingsHelper.AzurePasswordDb,
ApplicationName = SettingsHelper.AzureApplicationName,
DataSource = SettingsHelper.AzureSqlServer
};
UnitOfWork unitOfWork = new UnitOfWork();
ConfigurationDBDataContext context = new ConfigurationDBDataContext();
context.Empresas.Add(new Empresa()
{
Id = 1,
Nombre = "company name 1",
NIT = "873278423",
NombreRepresentanteLegal = "myself",
TelefonoRepresentanteLegal = "32894823",
NombreContacto = "myself",
TelefonoContacto = "32423"
});
context.SaveChanges();
var listofEmpresas = unitOfWork.EmpresaRepository.Get().ToList();
foreach(Empresa empresa in listofEmpresas)
{
DbUtils.CreateDatabaseIfNotExists(connStrBldr.ConnectionString, empresa.NIT);
sharding.RegisterNewShard(SettingsHelper.AzureSqlServer, empresa.NIT, connStrBldr.ConnectionString, empresa.Id);
}
}
}
}
the sharding.css
internal class Sharding
{
public ShardMapManager ShardMapManager { get; private set; }
public ListShardMap<int> ShardMap { get; private set; }
// Bootstrap Elastic Scale by creating a new shard map manager and a shard map on
// the shard map manager database if necessary.
public Sharding(string smmserver, string smmdatabase, string smmconnstr)
{
// Connection string with administrative credentials for the root database
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder(smmconnstr);
connStrBldr.DataSource = smmserver;
connStrBldr.InitialCatalog = smmdatabase;
// Deploy shard map manager.
ShardMapManager smm;
if (!ShardMapManagerFactory.TryGetSqlShardMapManager(connStrBldr.ConnectionString, ShardMapManagerLoadPolicy.Lazy, out smm))
{
this.ShardMapManager = ShardMapManagerFactory.CreateSqlShardMapManager(connStrBldr.ConnectionString);
}
else
{
this.ShardMapManager = smm;
}
ListShardMap<int> sm;
if (!ShardMapManager.TryGetListShardMap<int>("ElasticScaleWithEF", out sm))
{
this.ShardMap = ShardMapManager.CreateListShardMap<int>("ElasticScaleWithEF");
}
else
{
this.ShardMap = sm;
}
}
// Enter a new shard - i.e. an empty database - to the shard map, allocate a first tenant to it
// and kick off EF intialization of the database to deploy schema
// public void RegisterNewShard(string server, string database, string user, string pwd, string appname, int key)
public void RegisterNewShard(string server, string database, string connstr, int key)
{
Shard shard;
ShardLocation shardLocation = new ShardLocation(server, database);
if (!this.ShardMap.TryGetShard(shardLocation, out shard))
{
shard = this.ShardMap.CreateShard(shardLocation);
}
SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder(connstr);
connStrBldr.DataSource = server;
connStrBldr.InitialCatalog = database;
// Go into a DbContext to trigger migrations and schema deployment for the new shard.
// This requires an un-opened connection.
using (var db = new ElasticScaleContext<int>(connStrBldr.ConnectionString))
{
// Run a query to engage EF migrations
(from b in db.Terceros
select b).Count();
}
// Register the mapping of the tenant to the shard in the shard map.
// After this step, DDR on the shard map can be used
PointMapping<int> mapping;
if (!this.ShardMap.TryGetMappingForKey(key, out mapping))
{
this.ShardMap.CreatePointMapping(key, shard);
}
}
}
In the code implementing database creation: DbUtils.CreateDatabaseIfNotExists() -- you are probably using a T-SQL CREATE DATABASE command to Create an Azure database on a logical server. Currently CREATE DATABASE doesn't support specifying the Pool -- however an update to Azure DB is expected within the next month that will extend the functionality of CREATE DATABASE and ALTER DATABASE to specify the Pool name as well.
In the meantime, you can make a REST API call from the CreateDatabaseIfNotExists() routine to add the database to the pool once it is created, using the Update SQL Database command: https://msdn.microsoft.com/en-us/library/azure/mt163677.aspx.
However, making a rest call from inside your c# can be complex, and is discussed here: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client . It may be simpler to wait for the upcoming support in the CREATE DATABASE command, which would require a very small modification within your CreateDatabaseIfNotExists() routine.

Changing FullName programmatically in CRM Online (2011)

I am attempting to change the "FullName" field of existing CRM system users in our Dynamics CRM 2011 Online account. I have already made the change in settings to update all future users to the format "Last, First" ... so this is for changing the existing users.
I read the best way is to do this programmatically using the CRM SDK. When I perform the actual Update command, I receive an unspecified error from the SDK: Additional information: The property IsLicensed cannot be modified.
Although I'm querying all columns for entity object SystemUsers, I'm only changing the FullName field. Has anyone else had experience with this? My code is below, I'm running this as a console app to step through each SystemUser.
static void Main(string[] args)
{
string connStr = ConfigurationManager.ConnectionStrings["CRMOnline"].ToString();
CrmConnection conn = CrmConnection.Parse(connStr);
conn.DeviceCredentials = DeviceIdManager.LoadOrRegisterDevice();
using (OrganizationService svc = new OrganizationService(conn))
{
QueryExpression qry = new QueryExpression();
qry.ColumnSet = new ColumnSet(true); // get all columns
qry.EntityName = CRMO.SystemUser.EntityLogicalName; // get entity object SystemUser
qry.Criteria.AddCondition(new ConditionExpression("calendarid", ConditionOperator.NotNull)); // but non-builtin users
EntityCollection col = svc.RetrieveMultiple(qry); // executes query
foreach (Entity ent in col.Entities)
{
Console.WriteLine();
Console.WriteLine("Current Fullname: " + ent.Attributes["fullname"].ToString());
Console.Write("Change? y/N: ");
string ans = Console.ReadLine();
if (ans.ToLower() == "y")
{
Console.Write("New Name: ");
string newname = Console.ReadLine();
if (newname != "")
{
ent.Attributes["fullname"] = newname;
svc.Update(ent); // fails here with SDK error: "Additional information: The property IsLicensed cannot be modified."
}
}
}
Console.WriteLine();
Console.WriteLine("--- Done ---");
Console.ReadLine();
}
}
Rule 28 of the Crm SDK, don't ever perform updates by performing a select, which returns back more fields than what you are planning to update. Any fields in the attribute collection of the Entity will be updated even if they haven't changed. Instead, instantiate a new entity locally, set the id and whatever attributes you want to update and update it.
On a side note, you can't update the full name of a System User. You have to update the individual pieces. So your code should really look like this:
static void Main(string[] args)
{
string connStr = ConfigurationManager.ConnectionStrings["CRMOnline"];
CrmConnection conn = CrmConnection.Parse(connStr);
conn.DeviceCredentials = DeviceIdManager.LoadOrRegisterDevice();
using (OrganizationService svc = new OrganizationService(conn))
{
QueryExpression qry = new QueryExpression();
qry.ColumnSet = new ColumnSet("firstname", "lastname", "fullname"); // get only what is needed for performance reasons
qry.EntityName = CRMO.SystemUser.EntityLogicalName; // get entity object SystemUser
qry.Criteria.AddCondition(new ConditionExpression("calendarid", ConditionOperator.NotNull)); // but non-builtin users
EntityCollection col = svc.RetrieveMultiple(qry); // executes query
foreach (Entity ent in col.Entities)
{
Console.WriteLine();
Console.WriteLine("Current Fullname: " + ent["fullname"].ToString());
Console.Write("Update? Y/N: ");
string ans = Console.ReadLine();
if (ans.ToLower() == "y")
{
// Create a new entity, setting the id and whatever attributes that need to be updated
var updateEntity = new Entity { Id = ent.Id };
updateEntity["firstname"] = ent["firstname"];
updateEntity["lastname"] = ent["lastname"];
svc.Update(updateEntity);
}
}
Console.WriteLine();
Console.WriteLine("--- Done ---");
Console.ReadLine();
}
}
Notes:
Only retrieve the columns you actually need
Create an update entity that only contains the fields you want to update
Remember that FullName is readonly
This may also be helpful
This is so others reading this can use this solution to change the FullName in CRM Online.
So in my case, where I needed to change the FullName of existing CRM users from "First Last" to "Last, First", I was able to perform regular Office 365 admin functions to complete this.
First, I changed the format in CRM Settings > System Settings to "Last Name, First Name".
Then, for each user I needed to have changed, I used the Office 365 Admin Center and edited their licenses. Un-assign the CRM license from the user and click SAVE. Wait about a minute or two for the changes to take affect. Next, go back into that same user management and re-assign the CRM license to the user, click SAVE. Wait a few minutes and you will see the FullName in CRM should be in the correct format.

c# Entity Framework EF 4.1 Change Schema and Database name at runtime

I´ve searched for some topics, but did not find a concrete solution to my problem.
My app is a c# commercial app. I´m using EF 4.1 database first. I generate the model from a development database connection and that create a Model.edmx file and all EF stuff pretty fine.
My goal is to deliver an appplication to the customer and let him freely create the database and database user at his own. Do do it, at runtime I would get the username, password, database connection and schema name parameters to connect to customer database. In that way, to deploy the application all I need is to ask the customer to create a database and add the database parameters to the app config file.
So, myy goal is to change the connection string and schema parameter at runtime, without changing att all the auto generated edmx file, not touching the VS generated code.
I have looked around and found:
For EF earlier versions:
Changing schema name on runtime - Entity Framework
http://efmodeladapter.codeplex.com
All other posts are going around that. I tryed even to use the first post code with no success.
But I´ve seen that EF 4.1 comes with better support tools to do it, but I could not find references or examples to it. It´s important not to change the auto generated code from VS.
I´m pretty new to EF, so I would like to ask for help on accomplish the following tasks:
a) Change connection string at runtime adding my username, password and database server/port parameters
b) Change database schema
I´m using Oracle as a database server (that makes things worst as Oracle mixes schema and users together).
Actually, I needed solution for this too. I quickly whipped up solution, which works nicely. I didn't find much information about this in Internet, so I am not sure about the "EF 4.1 comes with better support tools to do it".
The concrete example "Changing schema name on runtime - Entity framework" didn't entirely work for me, however with some minor modifications I got it working.
Here is a DatabaseUtils class that can do it:
internal static class DatabaseUtils
{
/// <summary>
/// Builds the connection string for Entity framework.
/// </summary>
/// <returns></returns>
public static EntityConnection BuildConnection(BuildConnectionParams buildConnectionParams)
{
var sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = buildConnectionParams.ServerName,
InitialCatalog = buildConnectionParams.DatabaseName,
IntegratedSecurity = true
};
var providerString = sqlBuilder.ToString();
var entityBuilder = new EntityConnectionStringBuilder
{
Provider = buildConnectionParams.ProviderName,
ProviderConnectionString = providerString,
Metadata = string.Format(#"res://*/{0}.csdl|
res://*/{0}.ssdl|
res://*/{0}.msl", buildConnectionParams.ModelName)
};
return CreateConnection(buildConnectionParams.SchemaName, entityBuilder, buildConnectionParams.ModelName);
}
/// <summary>
/// Creates the EntityConnection, based on new schema & existing connectionString
/// </summary>
/// <param name="schemaName">Name of the schema.</param>
/// <param name="connectionBuilder"></param>
/// <param name="modelName">Name of the model.</param>
/// <returns></returns>
private static EntityConnection CreateConnection(string schemaName, EntityConnectionStringBuilder connectionBuilder, string modelName)
{
Func<string, Stream> generateStream =
extension => Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Concat(modelName, extension));
Action<IEnumerable<Stream>> disposeCollection = streams =>
{
if (streams == null)
return;
foreach (var stream in streams.Where(stream => stream != null))
stream.Dispose();
};
var conceptualReader = generateStream(".csdl");
var mappingReader = generateStream(".msl");
var storageReader = generateStream(".ssdl");
if (conceptualReader == null || mappingReader == null || storageReader == null)
{
disposeCollection(new[] { conceptualReader, mappingReader, storageReader });
return null;
}
var storageXml = XElement.Load(storageReader);
foreach (var entitySet in storageXml.Descendants())
{
var schemaAttribute = entitySet.Attributes("Schema").FirstOrDefault();
if (schemaAttribute != null)
schemaAttribute.SetValue(schemaName);
}
storageXml.CreateReader();
var workspace = new MetadataWorkspace();
var storageCollection = new StoreItemCollection(new[] { storageXml.CreateReader() });
var conceptualCollection = new EdmItemCollection(new[] { XmlReader.Create(conceptualReader) });
var mappingCollection = new StorageMappingItemCollection(conceptualCollection,
storageCollection,
new[] { XmlReader.Create(mappingReader) });
workspace.RegisterItemCollection(conceptualCollection);
workspace.RegisterItemCollection(storageCollection);
workspace.RegisterItemCollection(mappingCollection);
var connection = DbProviderFactories.GetFactory(connectionBuilder.Provider).CreateConnection();
if (connection == null)
{
disposeCollection(new[] { conceptualReader, mappingReader, storageReader });
return null;
}
connection.ConnectionString = connectionBuilder.ProviderConnectionString;
return new EntityConnection(workspace, connection);
}
}
Usage:
/// <summary>
/// Initializes a new instance of the <see cref="DynamicAQDContext"/> class.
/// </summary>
public DynamicAQDContext()
{
var entityConnection = DatabaseUtils.BuildConnection(new BuildConnectionParams
{
ProviderName = "System.Data.SqlClient",
ServerName = "localhost\\",
DatabaseName = "",
ModelName = "YOURMODEL",
SchemaName = "SCHEMA"
});
if(entityConnection == null)
throw new Exception("Can't create EntityConnection");
_entities = new LINKEntities(entityConnection);
}
more info can be found here: http://bestplayah.com/entity-framework-dynamic-schema-changes-using-database-first-approach/

Categories