Generic methods with entity framework - c#

I have a question about using a generic method with the entity framework.
I am using this example model
Data Model
And this is the code in my webform this code to populate the object.
var user = new User();
var selectedTitles = new List<UserTitle>();
var selectedDisabilities = new List<UserDisability>();
var t = titleRepository.SearchFor(d => d.Id==1 || d.Id ==2);
foreach (var temp in t)
{
selectedTitles.Add(new UserTitle { IsPublic = true, Title = temp, User = user });
}
var ds = disabilityRepository.SearchFor(d => d.Id==1 || d.Id ==2);
foreach (var temp in ds)
{
selectedDisabilities.Add(new UserDisability { IsPublic = true, Disability = temp, User = user });
}
user.FirstName = "Johnathan";
user.LastName = "Rifkin";
user.UserTitles = selectedTitles;
user.UserDisabilities = selectedDisabilities;
userRepository.Insert(user);
As you can see when populating the “UserTitles” and “UserDisabilities” properties the code is very similar, so rather than duplicate the code I would like to create a generic method that I can use to populate both the “UserTitles” and “UserDisabilities” and any other properties that I'll need in future.
Thanks in advance

Related

How to add distinct value in database using Entity Framework

IEnumerable<WebsiteWebPage> data = GetWebPages();
foreach (var value in data)
{
if (value.WebPage.Contains(".htm"))
{
WebsiteWebPage pagesinfo = new WebsiteWebPage();
pagesinfo.WebPage = value.WebPage;
pagesinfo.WebsiteId = websiteid;
db.WebsiteWebPages.Add(pagesinfo);
}
}
db.SaveChanges();
I want to add only distinct values to database in above code. Kindly help me how to do it as I am not able to find any solution.
IEnumerable<WebsiteWebPage> data = GetWebPages();
foreach (var value in data)
{
if (value.WebPage.Contains(".htm"))
{
var a = db.WebsiteWebPages.Where(i => i.WebPage == value.WebPage.ToString()).ToList();
if (a.Count == 0)
{
WebsiteWebPage pagesinfo = new WebsiteWebPage();
pagesinfo.WebPage = value.WebPage;
pagesinfo.WebsiteId = websiteid;
db.WebsiteWebPages.Add(pagesinfo);
db.SaveChanges();
}
}
}
This is the code that I used to add distinct data.I hope it helps
In addition to the code sample Furkan Öztürk supplied, Make sure your DB has a constraint so that you cannot enter duplicate values in the column. Belt and braces approach.
I assume that by "distinct values" you mean "distinct value.WebPage values":
// get existing values (if you ever need this)
var existingWebPages = db.WebsiteWebPages.Select(v => v.WebPage);
// get your pages
var webPages = GetWebPages().Where(v => v.WebPage.Contains(".htm"));
// get distinct WebPage values except existing ones
var distinctWebPages = webPages.Select(v => v.WebPage).Distinct().Except(existingWebPages);
// create WebsiteWebPage objects
var websiteWebPages = distinctWebPages.Select(v =>
new WebsiteWebPage { WebPage = v, WebsiteId = websiteid});
// save all at once
db.WebsiteWebPages.AddRange(websiteWebPages);
db.SaveChanges();
Assuming that you need them to be unique by WebPage and WebSiteId
IEnumerable<WebsiteWebPage> data = GetWebPages();
foreach (var value in data)
{
if (value.WebPage.Contains(".htm"))
{
WebsiteWebPage pagesinfo = new WebsiteWebPage();
if (db.WebsiteWebPages.All(c=>c.WebPage != value.WebPage|| c.WebsiteId != websiteid))
{
pagesinfo.WebPage = value.WebPage;
pagesinfo.WebsiteId = websiteid;
db.WebsiteWebPages.Add(pagesinfo);
}
}
}
db.SaveChanges();
UPDATE
To optimize this (given that your table contains much more data than your current list), override your equals in WebsiteWebPage class to define your uniqueness criteria then:
var myWebsiteWebPages = data.select(x=> new WebsiteWebPage { WebPage = x.WebPage, WebsiteId = websiteid}).Distinct();
var duplicates = db.WebsiteWebPages.Where(x=> myWebsiteWebPage.Contains(x));
db.WebsiteWebPages.AddRange(myWebsiteWebPages.Where(x=> !duplicates.Contains(x)));
this is a one database query to retrieve ONLY duplicates and then removing them from the list
You can use the following code,
IEnumerable<WebsiteWebPage> data = GetWebPages();
var templist = new List<WebsiteWebPage>();
foreach (var value in data)
{
if (value.WebPage.Contains(".htm"))
{
WebsiteWebPage pagesinfo = new WebsiteWebPage();
pagesinfo.WebPage = value.WebPage;
pagesinfo.WebsiteId = websiteid;
templist.Add(pagesinfo);
}
}
var distinctList = templist.GroupBy(x => x.WebsiteId).Select(group => group.First()).ToList();
db.WebsiteWebPages.AddRange(distinctList);
db.SaveChanges();
Or you can use MoreLINQ here to filter distinct the list by parameter like,
var res = tempList.Distinct(x=>x.WebsiteId).ToList();
db.WebsiteWebPages.AddRange(res);
db.SaveChanges();

Listing in WCF Entity

I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.

Cannot implicitly convert type 'System.Linq.IQueryable?

here is my code which is giving me above error
public ActionResult Edit(int id = 0)
{
KBS_Virtual_TrainingEntities db = new KBS_Virtual_TrainingEntities();
UsersContext ctx = new UsersContext();
UserProfile model = ctx.UserProfiles.Find(id);
List<CourseSubscription> user_Course_subscriptions = new List<CourseSubscription>();
foreach (UserSubscription sub in db.UserSubscriptions)
{
if (sub.ID == id)
{
user_Course_subscriptions.Add(sub.CourseSubscription);
}
}
List<CourseSubscription> not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions);
var coursesList = from courses in not_subscribe
select new SelectListItem
{
Text = courses.Course.Name,
Value = courses.Course.ID
.ToString()
};
var CoursesTYPE = from CourseTypes in db.CourseTypes.ToList()
select new SelectListItem
{
Text = CourseTypes.Name,
Value = CourseTypes.ID
.ToString()
};
ViewBag.CourseID = coursesList;
ViewBag.type = CoursesTYPE;
return View(model);
}
I am trying to find Course Subscription that are not subscribe by the current user by using the above code but its not working?
You're missing ToList on the results from your Except function. Do a ToList like so:
List<CourseSubscription> not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions).ToList();
Or since in your code you're not doing anything that needs a list, simply var it or assign the correct type to it such as IQueryable<CourseSubscription> to it.
var not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions);

Dynamics Crm: Get metadata for statuscode/statecode mapping

In Dynamics CRM 2011, on the Incident entity, the "Status Reason" optionset (aka statuscode) is related to the "Status" optionset (aka statecode)
e.g. see this screenshot
When I use the API to retrieve the Status Reason optionset, like so:
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "incident",
LogicalName = "statuscode",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)serv.Execute(attributeRequest);
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)attrMetadata;
var dict = new Dictionary<int?, string>();
foreach (OptionMetadata optionMeta in statusMetadata.OptionSet.Options)
{
dict.Add(optionMeta.Value, optionMeta.Label.UserLocalizedLabel.Label);
}
It works in that I get the whole list of "Status Reason" (statuscode) options. However, I dont get any info about which "Status Reason" (statuscode) options relate to which "Status" (statecode) options.
How do I get that information?
You already have everything try insert this code inside of foreach:
int stateOptionValue = (int)((StatusOptionMetadata)optionMeta).State;
See StatusAttributeMetaData.OptionSet.Options hierarchy can return a type called StatusOptionMetadata if you use the State property of the StatusOptionMetadata, it will return the statecode this statuscode belongs to.
Here is how you can get it by querying the database
SELECT distinct e.LogicalName as entity,
smState.Value AS stateCode,
smstate.AttributeValue,
smStatus.Value AS [statuscode/statusreason],
smStatus.AttributeValue
FROM StatusMap sm
JOIN Entity e ON sm.ObjectTypeCode = e.ObjectTypeCode
JOIN StringMap smState ON smState.AttributeValue = sm.State
AND smState.ObjectTypeCode = e.ObjectTypeCode
AND smState.AttributeName = 'StateCode'
JOIN StringMap smStatus ON smStatus.AttributeValue = sm.Status
AND smStatus.ObjectTypeCode = e.ObjectTypeCode
AND smStatus.AttributeName = 'StatusCode'
WHERE e.LogicalName in ('lead')
ORDER BY e.LogicalName,
smState.AttributeValue,
smStatus.AttributeValue;
Here is working code that will output State/Status mapping for a given entity (you just need to provide the orgServiceProxy):
var dictState = new Dictionary<int, OptionMetadata>();
var dictStatus = new Dictionary<int, List<OptionMetadata>>();
string entityName = "lead";
int count=0;
using (var orgServiceProxy = GetOrgServiceProxy(orgServiceUriOnLine))
{
RetrieveAttributeResponse attributeResponse = GetAttributeData(orgServiceProxy, entityName, "statecode");
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
StateAttributeMetadata stateMetadata = (StateAttributeMetadata)attrMetadata;
foreach (OptionMetadata optionMeta in stateMetadata.OptionSet.Options)
{
dictState.Add(optionMeta.Value.Value,optionMeta);
dictStatus.Add(optionMeta.Value.Value,new List<OptionMetadata>());
}
attributeResponse = GetAttributeData(orgServiceProxy, entityName, "statuscode");
attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)attrMetadata;
foreach (OptionMetadata optionMeta in statusMetadata.OptionSet.Options)
{
int stateOptionValue = ((StatusOptionMetadata)optionMeta).State.Value;
var statusList = dictStatus[stateOptionValue];
statusList.Add(optionMeta);
count++;
}
}
Console.WriteLine($"Number of mappings: {count}");
foreach (var stateKvp in dictState.OrderBy(x=> x.Key))
{
Console.WriteLine($"State: {stateKvp.Value.Value}: {stateKvp.Value.Label.UserLocalizedLabel.Label}");
var statusList = dictStatus[stateKvp.Key];
Console.WriteLine($"\tStatuses");
foreach (var status in statusList.OrderBy(s => s.Value))
{
Console.WriteLine($"\t\t{stateKvp.Value.Value}: {status.Label.UserLocalizedLabel.Label}");
}
}

How can I write a LINQ to SQL query to update tags?

I have an image site where users can tag photos much like you can tag a question on Stackoverflow.
I have the following tables:
Images [ID, URL, etc]
Tags [ID, TagName]
ImageTag [TagID, ImageID]
I want to write a method with the signature:
public void UpdateImageTags(int imageId, IEnumerable<string> currentTags)
This method will do the following:
Create any new Tags in currentTags that don't already exist in the Tags table.
Get the old ImageTag's for an image.
Delete any ImageTag's that no longer exist in the currentTags
Add any ImageTag's that are new between the currentTags and oldTags.
Here is my attempt at that method:
public void UpdateImageTags(int imageId, IEnumerable<string> currentTags)
{
using (var db = new ImagesDataContext())
{
var oldTags = db.ImageTags.Where(it => it.ImageId == imageId).Select(it => it.Tag.TagName);
var added = currentTags.Except(oldTags);
var removed = oldTags.Except(currentTags);
// Add any new tags that need created
foreach (var tag in added)
{
if (!db.Tags.Any(t => t.TagName == tag))
{
db.Tags.InsertOnSubmit(new Tag { TagName = tag });
}
}
db.SubmitChanges();
// Delete any ImageTags that need deleted.
var deletedImageTags = db.ImageTags.Where(it => removed.Contains(it.Tag.TagName));
db.ImageTags.DeleteAllOnSubmit(deletedImageTags);
// Add any ImageTags that need added.
var addedImageTags = db.Tags.Where(t => added.Contains(t.TagName)).Select(t => new ImageTag { ImageId = imageId, TagId = t.TagId });
db.ImageTags.InsertAllOnSubmit(addedImageTags);
db.SubmitChanges();
}
}
However, this fails on the line:
db.ImageTags.DeleteAllOnSubmit(deletedImageTags);
With the error:
Local sequence cannot be used in LINQ to SQL implementations of query
operators except the Contains operator.
Is there an easier way I can handle the operation of adding new tags, deleting old ImageTags, adding new ImageTags in LINQ to SQL?
Seems like this would be easiest
public void UpdateImageTags(int imageId, IEnumerable<string> currentTags)
{
using (var db = new ImagesDataContext())
{
var image = db.Images.Where(it => it.ImageId == imageId).First()
image.Tags.Clear();
foreach(string s in currentTags)
{
image.Tags.Add(new Tag() { TagName = s});
}
db.SubmitChanges();
}
}
This might have to be modified slightly for LinqtoSQL. EF is what i have been using most recently. Also this is dependent on Lazy loading being enabled. If it is not, you will have to force the include of the image tags.
Here is a helper method to deal with many-to-many relationships:
public static void UpdateReferences<FK, FKV>(
this EntitySet<FK> refs,
Expression<Func<FK, FKV>> fkexpr,
IEnumerable<FKV> values)
where FK : class
where FKV : class
{
Func<FK, FKV> fkvalue = fkexpr.Compile();
var fkmaker = MakeMaker(fkexpr);
var fkdelete = MakeDeleter(fkexpr);
var fks = refs.Select(fkvalue).ToList();
var added = values.Except(fks);
var removed = fks.Except(values);
foreach (var add in added)
{
refs.Add(fkmaker(add));
}
foreach (var r in removed)
{
var res = refs.Single(x => fkvalue(x) == r);
refs.Remove(res);
fkdelete(res);
}
}
static Func<FKV, FK> MakeMaker<FKV, FK>(Expression<Func<FK, FKV>> fkexpr)
{
var me = fkexpr.Body as MemberExpression;
var par = Expression.Parameter(typeof(FKV), "fkv");
var maker = Expression.Lambda(
Expression.MemberInit(Expression.New(typeof(FK)),
Expression.Bind(me.Member, par)), par);
var cmaker = maker.Compile() as Func<FKV, FK>;
return cmaker;
}
static Action<FK> MakeDeleter<FK, FKV>(Expression<Func<FK, FKV>> fkexpr)
{
var me = fkexpr.Body as MemberExpression;
var pi = me.Member as PropertyInfo;
var assoc = Attribute.GetCustomAttribute(pi, typeof(AssociationAttribute))
as AssociationAttribute;
if (assoc == null || !assoc.DeleteOnNull)
{
throw new ArgumentException("DeleteOnNull must be set to true");
}
var par = Expression.Parameter(typeof(FK), "fk");
var maker = Expression.Lambda(
Expression.Call(par, pi.GetSetMethod(),
Expression.Convert(Expression.Constant(null), typeof(FKV))), par);
var cmaker = maker.Compile() as Action<FK>;
return cmaker;
}
Usage:
IEnumerable<Tag> values = ...;
Image e = ...;
e.ImageTags.UpdateReferences(x => x.Tag, tags);

Categories