entity framework - two people with the same data - c#

I want to map a two tables in entity framework 6 and need some help! It is for my chat application; I need to map user conversations into the database. Both group and private messages. For this question however, if you help me with the private messaging mapping, I should hopefully work out the group by myself :) anyway....
Each user can talk to any other user. They however share the same data, which is where I am struggling a bit: how to set the keys to the exact same data without duplication. This is what I have so far:
**EDIT - new code *****
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace CodeFirstNewDatabaseSample
{
static void Main(string[] args)
{
using(var db = new PrivateMessageContext())
{
Console.Write("Enter message: ");
var message = Console.ReadLine();
var userFrom = "userFrom";
var userTo = "userTo";
var messageDetail = new PrivateMessageDetail(MessageDate = DateTime.Now, FromUser = userFrom, message = message);
var pm = new PrivateMessageHeader { User1 = userFrom, User2 = userTo, TimeStamp = DateTime.Now };
pm.Messages.Add(messageDetail);
db.PrivateMessages.Add(pm);
db.SaveChanges();
// Display all Blogs from the database
foreach(var pmsg in db.PrivateMessages)
{
var query = pmsg;
Console.WriteLine(pmsg.Message);
}
Console.ReadKey();
}
}
}
public class PrivateMessage
{
public int PrivateMessageId { get; set; }
public string Message { get; set; }
public DateTime TimeStamp { get; set; }
// public int User1Id { get; set; }
public virtual string user1 { get; set; }
// public virtual User user1 { get; set; }
public virtual string user2 { get; set; }
//public int User1Id { get; set; }
// public virtual User user2 { get; set; }
}
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
public class PrivateMessageContext : DbContext
{
public DbSet<PrivateMessage> PrivateMessages { get; set; }
}
public class Send
{
/* void Send(userTo, userFrom, message)
{
using (var db = new PrivateMessageContext()) {
var query = from pm in db.PrivateMessages;
foreach(var msg in pm)
{
var user1 = msg.user1;
var user2 = msg.user2;
if ( (user1==userTo && user2==userFrom) || (user1==userFrom && user2==userTo))
{
msg.Message += message;
return;
}
else {
// pair doesn't exist
var PrivateMessage = new PrivateMessage { user1 = userFrom; user2 = userTo; TimeStamp = DateTime.Now; Message = message; };
db.PrivateMessages.Add(PrivateMessage);
db.SaveChanges();
}
}
}*/
}
}
I am now stuck on two things - how to make a callable class which checks if there is previous message history (the Send() ) and how to use the User username instead of strings...
Thank you
*update 3*
static void Main(string[] args)
{
using(var db = new PrivateMessageContext())
{
Console.Write("Enter message: ");
var message = Console.ReadLine();
var userFrom = "userFrom";
var userTo = "userTo";
var messageDetail = new PrivateMessageDetail(MessageDate = DateTime.Now, FromUser = userFrom, message = message);
var pm = new PrivateMessageHeader { User1 = userFrom, User2 = userTo, TimeStamp = DateTime.Now, Message = messageDetail };
db.PrivateMessages.Add(pm);
db.SaveChanges();
// Display all Blogs from the database
foreach(var pmsg in db.PrivateMessages)
{
var query = pmsg;
Console.WriteLine(pmsg.Message);
}
Console.ReadKey();
}
}
}
public class PrivateMessageContext : DbContext
{
public DbSet<PrivateMessageHeader> PrivateMessages { get; set; }
}

What you probably want is some kind of master/detail. What you would do is create a PrivateMessageHeader type, and this would contain the participants in the private message. Then you would have a PrivateMessageDetail type that would contain the actual messages. There would be a 1 to many association between Header and details.
So something like this:
public class PrivateMessageHeader {
public PrivateMessageHeader() { Messages = new List<PrivateMessageDetail>; }
public int PrivateMessageHeaderId {get;set;}
public DateTime ThreadTime {get;set;} // Date of the start of thread
public string User1 {get;set;}
public string User2 {get;set;} // this could be made to a list to allow multiples
public ICollection<PrivateMessageDetail> Messages {get;set;}
}
public class PrivateMessageDetail {
public int PrivateMessageDetailId {get;set;}
public DateTime MessageDate {get;set;}
public string FromUser {get;set;} // Don't need ToUser, it's already in header
public string Message {get;set;}
public PrivateMessageHeader parent {get;set;}
}

Related

Allowing a user to select column headers to import

I'm using LINQtoCSV within a program that allows the user to import an order from a CSV file. I have all the code working however, if the CSV file doesn't have the exact column headers then it doesn't work.
Below is my class that LINQtoCSV reads into -
public class orderProduct
{
public orderProduct() { }
public string product { get; set; }
public string price { get; set; }
public string orderQty { get; set; }
public string value { get; set; }
public string calculateValue()
{
return (Convert.ToDouble(price) * Convert.ToDouble(orderQty)).ToString();
}
}
If the CSV file doesn't have the exact headers it won't work. The data I actually only need is the first 4 strings.
Below is my function that actually reads in the data.
private void csvParse()
{
// order.Clear();
string fileName = txt_filePath.Text.ToString().Trim();
try
{
CsvContext cc = new CsvContext();
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
IEnumerable<orderProduct> fromCSV = cc.Read<orderProduct>(fileName, inputFileDescription);
foreach (var d in fromCSV)
{
MessageBox.Show($#"Product:{d.product},Quantity:""{d.orderQty}"",Price:""{d.price}""");
orderReturn.Add(d);
}
this.DialogResult = DialogResult.Yes;
this.Close();
}
catch (Exception ex)
{
if (ex.ToString().Contains("being used by another process"))
{
MessageBox.Show("Error: Please close the file in Excel and try again");
}
else
{
MessageBox.Show(ex.ToString());
}
}
}
I want the user to be able to just pass in a file and then select the relevant columns which relate to the corresponding values and then read in the data ignoring any columns that haven't been selected.
Hope this all makes sense, is something like this possible within LINQtoCSV
You have to add IgnoreUnknownColumns = true to your CsvFileDescription
CSV:
product,price,someColumn,orderQty,value,otherColumn
my product,$123,xx,2,$246,aa
my other product,$10,yy,3,$30,bb
Working code (I modified your code a little bit, to run it in a console)
using System;
using System.Collections.Generic;
using LINQtoCSV;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
csvParse();
Console.ReadLine();
}
private static void csvParse()
{
string fileName = "../../../test.csv"; // provide a valid path to the file
CsvContext cc = new CsvContext();
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true,
IgnoreUnknownColumns = true // add this line
};
IEnumerable<orderProduct> fromCSV = cc.Read<orderProduct>(fileName, inputFileDescription);
foreach (var d in fromCSV)
{
Console.WriteLine($#"Product:{d.product},Quantity:""{d.orderQty}"",Price:""{d.price}""");
}
}
}
public class orderProduct
{
public orderProduct() { }
public string product { get; set; }
public string price { get; set; }
public string orderQty { get; set; }
public string value { get; set; }
public string calculateValue()
{
return (Convert.ToDouble(price) * Convert.ToDouble(orderQty)).ToString();
}
}
}
Output:
Product:my product,Quantity:"2",Price:"$123"
Product:my other product,Quantity:"3",Price:"$10"
If your properties have different names than CSV columns, you should use CsvColumn attribute:
public class OrderProduct
{
[CsvColumn(Name = "product")]
public string Product { get; set; }
[CsvColumn(Name = "price")]
public string Price { get; set; }
[CsvColumn(Name = "orderQty")]
public string OrderQuantity { get; set; }
public string Value { get; set; }
public string calculateValue()
{
return (Convert.ToDouble(Price) * Convert.ToDouble(OrderQuantity)).ToString();
}
}
Or if you prefer mapping columns by their indices:
public class OrderProduct
{
[CsvColumn(FieldIndex = 0)]
public string Product { get; set; }
[CsvColumn(FieldIndex = 1)]
public string Price { get; set; }
[CsvColumn(FieldIndex = 2)]
public string OrderQuantity { get; set; }
public string Value { get; set; }
public string calculateValue()
{
return (Convert.ToDouble(Price) * Convert.ToDouble(OrderQuantity)).ToString();
}
}
If you have to specify the columns on the fly, the only way seems to be to read raw data and process it yourself (the solution is based on this article):
internal class DataRow : List<DataRowItem>, IDataRow
{
}
...
int productColumnIndex = 0; // your users will provide it
var fromCSV = cc.Read<DataRow>(fileName);
foreach (var row in fromCSV)
{
var orderProduct = new OrderProduct
{
Product = row[productColumnIndex].Value,
};
Console.WriteLine(orderProduct.Product);
}

Get Collections from object using reflection and getCount (.net 4)

I have a requirement to reflect on a object get all properties that are collections and
1)GetCount for each collection
2)GetTotalCount (allCollectionCount)
3)Call a method with this collection.
Below is what I have done so far with a made up noddy structure for semplicity.
I am stuck in how to call this method and how to get count for collection.
Any suggestions?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
var request = GetDataRequest();
//Get all properties
List<PropertyInfo> propInfoList =
new List<PropertyInfo>(request.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public));
//Get collections only
var myClassCollections=propInfoList.Where(xxx => xxx.PropertyType.GetInterfaces().Any(x => x == typeof (IEnumerable))).ToList();
var totalCountForAllCollections=????
foreach (var col in myClassCollections)
{
//How do I call my Method DoSomething
// DoSomething<?>(col.?????)
}
}
public void DoSomething<T>(List<T> objectCollection)
{
//etc...
}
private static DataRequest GetDataRequest()
{
DataRequest request = new DataRequest();
request.Addresses.Add(new Address
{
Id = 1,
City = "London",
Postcode = "32131",
Street = "London Road"
});
request.Addresses.Add(new Address
{
Id = 2,
City = "NewYork",
Postcode = "3432",
Street = "NewYork Road"
});
request.Customers.Add(new Customer
{
Id = 1,
Name = "Jo",
Surname = "Bloggs",
});
request.Customers.Add(new Customer
{
Id = 1,
Name = "Jon",
Surname = "Bloggs2",
});
request.Customers.Add(new Customer
{
Id = 1,
Name = "Jonny",
Surname = "Bloggs3",
});
return request;
}
}
public class DataRequest
{
public DataRequest()
{
Customers = new List<Customer>();
Orders = new List<Order>();
Addresses = new List<Address>();
}
public List<Customer> Customers { get; set; }
public List<Order> Orders { get; set; }
public List<Address> Addresses { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
public class Order
{
public int Id { get; set; }
public string Name { get; set; }
public string OrderNo { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
}
}
quick and dirty, here you go...
// ..
static class Program
{
static void Main()
{
var request = GetDataRequest();
//Get propertyValues for properties that are enumerable (i.e. lists,arrays etc)
var collectionProperties = request.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(propertInfo => propertInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEnumerable)))
.Select(p => p.GetValue(request, null))
.Cast<IEnumerable<object>>().ToList();
var totalCountForAllCollections = 0;
// iterate through the list of propertyValues
foreach (var collectionPropertyValue in collectionProperties)
{
totalCountForAllCollections += collectionPropertyValue.Count();
collectionPropertyValue.DoSomething();
}
System.Console.WriteLine("The total count for all collections is : {0}", totalCountForAllCollections);
System.Console.WriteLine("press any key to exit");
System.Console.ReadLine();
}
public static void DoSomething<T>(this IEnumerable<T> objectCollection)
{
//etc...
// N.B. you will have to use typeof(T) to implement logic specific to the type
// If the logic in this method is non-specific to the typeof(T) then Implement logic accordingly
System.Console.WriteLine("The type of the collection is: {0}", objectCollection.GetType());
System.Console.WriteLine("The count of items in this collection is:{0}", objectCollection.Count());
}
// ..
}
// ..

Entity framework error: context changed since the database was created

I am getting the following error:
An unhandled exception of type 'System.InvalidOperationException'
occurred in EntityFramework.dll
Additional information: The model backing the 'PrivateMessageContext'
context has changed since the database was created. Consider using
Code First Migrations to update the database
(http://go.microsoft.com/fwlink/?
But why has it changed? All I want is to get the new message, check if the users have previous message history and either create a new message history or append their current...
I am trying to test the send method, so I want to print out the previous messages each time a new message is added
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace CodeFirstNewDatabaseSample
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter message: ");
var message = Console.ReadLine();
var userFrom = "userFrom";
var userTo = "userTo";
Methods test = new Methods();
for(var i=0; i < 10; i++)
{
test.StoreMessage(userTo, userFrom, message);
Console.Write("Enter message: ");
message = Console.ReadLine();
}
}
}
public class PrivateMessageContext : DbContext
{
public DbSet<PrivateMessageHeader> PrivateMessages { get; set; }
}
public class PrivateMessageHeader
{
public PrivateMessageHeader() { this.Messages = new List<PrivateMessageDetail>(); }
public int PrivateMessageHeaderId { get; set; }
public DateTime TimeStamp { get; set; } // Date of the start of thread
public string User1 { get; set; }
public string User2 { get; set; } // this could be made to a list to allow multiples
public ICollection<PrivateMessageDetail> Messages { get; set; }
}
public class PrivateMessageDetail
{
public int PrivateMessageDetailId { get; set; }
public DateTime MessageDate { get; set; }
public string FromUser { get; set; } // Don't need ToUser, it's already in header
public string Message { get; set; }
public PrivateMessageHeader parent { get; set; }
}
public class Methods
{
public void StoreMessage(string userTo, string userFrom, string InputMessage)
{
using (var db = new PrivateMessageContext())
{
var collection = from pm in db.PrivateMessages select pm;
foreach(var msg in collection)
{
var user1 = msg.User1;
var user2 = msg.User2;
if ( (user1==userTo && user2==userFrom) || (user1==userFrom && user2==userTo))
{
var msgDetail = new PrivateMessageDetail();
msgDetail.FromUser = userFrom;
msgDetail.Message = InputMessage;
msgDetail.MessageDate = DateTime.Now;
msg.Messages.Add(msgDetail);
db.SaveChanges();
return;
}
}
// pair doesn't exist
var PrivateMessage = new PrivateMessageDetail();
PrivateMessage.MessageDate = DateTime.Now;
PrivateMessage.FromUser = userFrom;
PrivateMessage.Message = InputMessage;
var newCollection = new PrivateMessageHeader();
newCollection.TimeStamp = DateTime.Now;
newCollection.User1 = userTo;
newCollection.User2 = userFrom;
newCollection.Messages.Add(PrivateMessage);
db.PrivateMessages.Add(newCollection);
db.SaveChanges();
var iterator = 0;
// Display all messages from the database
foreach (var pmsg in db.PrivateMessages)
{
var query = pmsg;
var list = pmsg.Messages.ToList();
foreach (var item in list)
{
Console.WriteLine("msg" + iterator + ": " + item.ToString());
}
iterator++;
}
Console.ReadKey();
}
}
}
}
Many thanks
One of the sources I use for this issue is the Package Manager Console in VS2012. By using the Enable-Migrations command, along with the EnableAutomaticMigations flag, and then adding the Migration info into the project, I can update the database with any Code-First model changes that will not "break" the database, or my code. You won't have to manually add anything into the project, this is all done for you. If you forget to enable automatic migrations, you can manually edit this in the Configuration file that is added during this process. I believe that this process has been around since VS2008, but don't quote me on that. I have used this since VS2010 and has worked in both MVC and MVVM for both web and desktop. One of the articles I use on MSDN is here: http://msdn.microsoft.com/en-us/data/JJ591621.aspx, and you can also look for tutorials from John Galloway that explain this in detail.
Have you tried Database.SetInitializer<PrivateMessageContext>(null);?
Try to change your Context as follows.
public class PrivateMessageContext : DbContext
{
public DbSet<PrivateMessageHeader> PrivateMessages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
Database.SetInitializer<PrivateMessageContext>(null);
}
}
More info here

Entity Framework - Conditionally include related entities

I maintain an API that, based on a request for a list of people, returns a different result set based on the request. For example, some API clients want to get a list of people and a list of their interactions, others want people and a list of their metadata. All this can be specified int he request to the API method that returns people.
This does not appear to work:
using (var dbcontext = new ExampleEntities())
{
var query = dbcontext.People.AsQueryable();
//determined in earlier application logic based on request
if(includeMetadata)
{
query = query.Include("metadata");
}
//determined in earlier application logic based on request
if(includeInteractions)
{
query = query.Include("interactions");
}
/* ...SNIP... */
}
What I don't want to do is this:
var query = dbcontext.People.Include("Metadata").Include("interactions");
which will mean every request to get a person will include ALL their related entities, even if the requesting API client does not need them.
I also don't want to code every possible combination of logic:
if(includeMetadata && includeInteractions)
{
var query = dbcontext.People.Include("Metadata").Include("interactions");
}
else if(includeMetadata)
{
var query = dbcontext.People.Include("Metadata");
}
else if(includeInteractions)
{
var query = dbcontext.People.Include("Interactions");
}
else
{
var query = dbcontext.People;
}
This will result in hard-to-maintain code, however, I realize I could code generate this if needed.
You can chain the IQueryable's
using (var dbcontext = new ExampleEntities())
{
var query = dbcontext.People.AsQueryable();
if(includeMetadata)
{
query = query.Include("metadata");
}
if(includeInteractions)
{
query = query.Include("interactions");
}
}
Your first example should work if you replace u with query
u = u.Include("metadata");
with
query = query.Include("metadata");
Works fine here... checking the sql statements with the EF 6 Log handler
[TestClass]
public void SomeTestClass
{
[TestMethod]
public void ShouldLoadOnlyRequiredCollections()
{
Database.SetInitializer(new DropCreateDatabaseAlways<HomesContext>());
var db = new HomesContext();
Assert.IsFalse(db.Homes.Any());
var home = db.Homes.Create();
db.Homes.Add(home);
home.Staff.Add(new Staff { Name = "wilma" });
home.Staff.Add(new Staff { Name = "betty" });
home.Residents.Add(new Resident { Name = "fred" });
home.Residents.Add(new Resident { Name = "barney" });
db.SaveChanges();
db = null;
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<HomesContext>());
var sb = new StringBuilder();
db = new HomesContext();
db.Database.Log = ((s) => { sb.Append(s + "\r"); });
Assert.IsTrue(db.Homes.Any());
string log;
log = sb.ToString();
Assert.IsTrue(sb.ToString().Contains("FROM [dbo].[Homes]"));
sb = new StringBuilder(); //ok get residents
var q = db.Homes.Include("Residents");
Assert.IsTrue(string.IsNullOrEmpty(sb.ToString()));
var lst = q.ToList();
log = sb.ToString();
Assert.IsTrue(sb.ToString().Contains("[dbo].[Homes]"));
Assert.IsTrue(sb.ToString().Contains("[dbo].[Residents]"));
Assert.IsTrue(!sb.ToString().Contains("[dbo].[Staff]"));
sb = new StringBuilder(); //get staff
q = db.Homes.Include("Staff");
Assert.IsTrue(string.IsNullOrEmpty(sb.ToString()));
lst = q.ToList();
log = sb.ToString();
Assert.IsTrue(log.Contains("[dbo].[Homes]"));
Assert.IsTrue(!log.Contains("[dbo].[Residents]"));
Assert.IsTrue(log.Contains("[dbo].[Staffs"));
sb = new StringBuilder(); //get residents and staff
q = db.Homes.Include("Staff");
q = q.Include("Residents");
lst = q.ToList();
log = sb.ToString();
Assert.IsTrue(log.Contains("[dbo].[Homes]"));
Assert.IsTrue(log.Contains("[dbo].[Residents]"));
Assert.IsTrue(log.Contains("[dbo].[Staffs]"));
}
}
public class HomesContext:DbContext
{
public DbSet<Home> Homes { get; set; }
}
public class Home
{
public Home()
{
Staff = new List<Staff>();
Residents = new List<Resident>();
}
public int HomeId { get; set; }
public string HomeName { get; set; }
public int MaxResidents { get; set; }
public int MaxStaff { get; set; }
public int CurrentResidents { get; set; }
[NotMapped]
public int CurrentStaff { get; set; }
public IList<Staff> Staff { get; set; }
public IList<Resident> Residents { get; set; }
}
public class Staff
{
public int StaffId { get; set; }
public string Name { get; set; }
public int HomeId { get; set; }
public Home Home { get; set; }
}
public class Resident
{
public int ResidentId { get; set; }
public string Name { get; set; }
public int HomeId { get; set; }
public Home Home { get; set; }
}

Cannot connect to database while using Entity Framework Code First

I wrote very simple class, that perfom data access.
It checks if line with that day exist in table and update her or create a new line.
public class DataAccessClass
{
public static DayWeather GetDayWeather(DateTime date)
{
try
{
using (var db = new Context())
{
var query =
(from day in db.DayWeather
where ((DateTime)day.DateOfDay).Date == date.Date
select new DayWeather((short)day.Temperature, (ushort)day.WindSpeed, (ushort)day.Pressure, (ushort)day.Humidity, day.Cloudiness, day.TypeRecip, (DateTime)day.DateOfDay)).First();
return query;
}
}
catch (Exception exp)
{
if (!EventLog.SourceExists("DataAccessSource"))
{
EventLog.CreateEventSource("DataAccessSource", "DataAccessErrorLog");
}
EventLog.WriteEntry("DataAccessSource", exp.Message);
throw new Exception("Problem with data get.");
}
}
public static void SaveDayWeather(DayWeather day)
{
try
{
using (var db = new Context())
{
var existingDay =
(from d in db.DayWeather
where ((DateTime)day.DateOfDay).Date == day.DateOfDay.Date
select d).SingleOrDefault<DayWeather>();
if (existingDay != null)
{
existingDay.Temperature = day.Temperature;
existingDay.WindSpeed = day.WindSpeed;
existingDay.Pressure = day.Pressure;
existingDay.Humidity = day.Humidity;
existingDay.Cloudiness = day.Cloudiness;
existingDay.TypeRecip = day.TypeRecip;
db.SaveChanges();
}
else
{
DayWeather newDay = new DayWeather();
newDay.DateOfDay = day.DateOfDay;
newDay.Temperature = day.Temperature;
newDay.WindSpeed = day.WindSpeed;
newDay.Pressure = day.Pressure;
newDay.Humidity = day.Humidity;
newDay.Cloudiness = day.Cloudiness;
newDay.TypeRecip = day.TypeRecip;
db.DayWeather.Add(newDay);
db.SaveChanges();
}
}
}
It use EF for generate database. The Contex class and class for save look like this:
public class DayWeather
{
public short Temperature { get; set; }
public ushort WindSpeed { get; set; }
public ushort Pressure { get; set; }
public ushort Humidity { get; set; }
public string Cloudiness { get; set; }
public string TypeRecip { get; set; }
public DateTime DateOfDay { get; set; }
public DayWeather(short Temperature, ushort WindSpeed, ushort Pressure, ushort Humidity, string Cloudiness, string TypeRecip, DateTime Date)
{
this.Temperature = Temperature;
this.WindSpeed = WindSpeed;
this.Pressure = Pressure;
this.Humidity = Humidity;
this.Cloudiness = Cloudiness;
this.TypeRecip = TypeRecip;
this.DateOfDay = Date;
}
public DayWeather()
{
}
}
internal class Context : DbContext
{
public DbSet<DayWeather> DayWeather { get; set; }
}
I call this methods by this code:
DataAccessClass.SaveDayWeather(new DayWeather(12, 12, 12, 12, "Yes", "rain", DateTime.Now));
DayWeather day = DataAccessClass.GetDayWeather(DateTime.Now);
Console.WriteLine(day.ToString());
Console.ReadKey();
It should generate new database, but error occurs. In message it write that can`t connect to the SQL Server.
Is somebody know what is wrong?
P.S. Sorry for my bad English.
P.P.S. I added EF by NuGet.
You can manually specify the connection string as follows
using (var db = new Context("connectionString"))
The default constructor looks up a connection string in the web.config with the same name as the derived context class Context.
If it fails to find one it defaults to
Data Source=.\SQLEXPRESS;
or
Data Source=(LocalDb)\v11.0;
depending on the version of sql server you are using.

Categories