Class IO in Data entity framework

public void PrintFaturen(int faturaID)
using (var db = new blejshpejtDBEntities1())
var mFatura = db.Shitjas.Single(c => c.ShitjaID == faturaID);
StringBuilder permbajtja = new StringBuilder();
foreach (var item in mFatura.ShitjaDetajets)
if (item is ShitjaDetajet)
ShitjaDetajet afd = (ShitjaDetajet)item;
if (mFatura.VleraTVSH.GetValueOrDefault(0))
permbajtja.AppendLine("S,1,______,_,__;" + afd.Artikulli.Emri + ";" +
afd.CmimiPerNjesi.GetValueOrDefault(0) + ";" +
afd.Sasia + ";1;1;2;0;" + "B" + afd.ShitjaDetajetID + ";0;");
else
permbajtja.AppendLine("S,1,______,_,__;" + afd.Artikulli.Emri + ";" +
afd.CmimiPerNjesi.GetValueOrDefault(0) + ";" +
afd.Sasia + ";1;1;1;0;" + "AP" + afd.ShitjaDetajetID + ";0;");
decimal llojiPageses = 0;
permbajtja.AppendLine("C,1,________,_,__;1;" + 0 + ";");
permbajtja.AppendLine("Q,1,______,_,__;1;" + "___________");
//permbajtja.AppendLine("Q,1,______,_,__;2; Ref Nr: " + mFatura.ID);
permbajtja.AppendLine("T,1,______,_,__;" + llojiPageses);
StreamWriter stram = new StreamWriter(@"C:\TEMP\FATURA.inp");
stram.Write(permbajtja.ToString());
stram.Flush();
stram.Close();
I need to write data in txt file  but I have error in this Line:
 if (mFatura.VleraTVSH.GetValueOrDefault(0)) error message  cannot implicitly convert type bool to decimal
variable  mFatura.VleraTVSH is decimal   and
afd.CmimiPerNjesi.GetValueOrDefault(0)
afd.CmimiPerNjesi.GetValueOrDefault(0)   error message is : 
decimal doesn't contain a definition for GetValueOrDefault

afd.CmimiPerNjesi.GetValueOrDefault(0)
afd.CmimiPerNjesi.GetValueOrDefault(0)
  error message is : 
decimal doesn't contain a definition for GetValueOrDefault
first work well but two another 
thnx for your help
Can you help me and for two another

Similar Messages

  • Add Data from DataGridView in Data entity framework

    private void ShtoArtikullin()
    //FaturatDetalet fd = new Faturatdetalet();
    System.Data.DataRow newrow = lvShitjetDetajet.NewRow();
    //fd.FaturaID = -1;
    int lastid = 1;
    //if (dtDetaletFatura.Rows.Count == null)
    lastid = lvShitjetDetajet.Rows.Count + 1;
    newrow["FaturaID"] = lastid;
    newrow["ArtikulliID"] = lvArtikujt.SelectedRows[0].Cells["ID"].Value;
    newrow["Emri"] = lvArtikujt.SelectedRows[0].Cells["Emri"].Value;
    newrow["Njesia"] = lvArtikujt.SelectedRows[0].Cells["Njesia"].Value;
    newrow["Sasia"] = 1;
    newrow["Cmimi"] = lvArtikujt.SelectedRows[0].Cells["Cmimi"].Value;
    newrow["Totali"] = lvArtikujt.SelectedRows[0].Cells["Cmimi"].Value;
    //DataRow r = newrow;
    //newrow["Barkodi"] = dgArtikujt.SelectedRows[0].Cells["Barkodi"].Value;
    dtDetaletFatura.Rows.Add(newrow);
    ////selektimi e percjell artikullin e fundit
    dgDetaletFat.Rows[dgDetaletFat.Rows.Count - 1].Selected = true;
    //dgDetaletFat.ClearSelection();
    //e fshin tekstin ne txtserch te artikullin e shtuar
    txtSearch.Text = "";
    I need this code to do in Data entity framework,this kode is to add data from one datagridview to another datagridview it work well in sqldataadapter but i need  to do in data entity framework  how to do this?

    If you add these entries to an observablecollection and put that in application.current.resources.  Use that same observablecollection in both datagrids. 
    When you add an entity in one DataGrid  then it will appear in the other one.
    Although it is not really what the sample is about, you can see a simple way to  share an observable collection across views in this:
    https://gallery.technet.microsoft.com/Dynamic-XAML-Composed-View-e087f3c1
    I don't quite follow where the selecting comes in with your code but that sample also uses the current item to share which is selected.
    I also recommend wrapping an entity in a row viewmodel.
    As I do in this:
    http://social.technet.microsoft.com/wiki/contents/articles/28209.wpf-entity-framework-mvvm-walk-through-1.aspx
    Please don't forget to upvote posts which you like and mark those which answer your question.
    My latest Technet article - Dynamic XAML

  • WCF Data Service from Entity Framework 5 in SharePoint 2013

    not sure which forum is best, so im going to throw it in here.
    I am working on a proof of concept. I want to create a WCF Data Service within sharepoint 2013. not only do i want to do that, i want to use the Entity Framework 5 to expose the data via OData. Now, I have crawled the internet and seen various examples of
    how to create wcf data services and wcf services in sharepoint 2010/2013. and have tried to apply those as needed to create this POC. So.. what I have done so far. 
    MonitoringData.cs
    [BasicHttpBindingServiceMetadataExchangeEndpoint]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    [System.Runtime.InteropServices.Guid("0185abf6-e8b8-42e2-9965-6bb644338077")]
    public class MonitoringData : DataService<MonitoringServiceEntities>
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetEntitySetAccessRule("*", EntitySetRights.AllWrite);
    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    MonitoringData.svc:
    <%@ServiceHost Language="C#" Debug="true"
    Service="$SharePoint.Type.0185abf6-e8b8-42e2-9965-6bb644338077.AssemblyQualifiedName$"
    Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressDataServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    upon deployment, this error when hitting the https://server/_vti_bin/poc/monitoringdata.svc/$metadata
    "The type 'xxxxxxxx', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could
    not be found."
    Breaking out the google-fu, i found that adding the dll to the <compilation> section was needed for the web.config. so i did that. and now i just get a blank screen with no errors.
    so i crack open fiddler. i see the following 
    200 http
    tunnel to
    server:443 0
    401 https
    server /_vti_bin/poc/monitoringdata.svc/$metadata
    16
    401
    https server
    /_vti_bin/poc/monitoringdata.svc/$metadata
    0
    404
    https server
    /_vti_bin/poc/monitoringdata.svc/$metadata
    0
    best i can see is that im either not authorized, and its returning null (which shouldnt be the case) or something is just busted.
    The goal is to use ntml auth and https to connect to this service. any ideas?

    One thing I found was that it's never worth the trouble to place the WCF service in a web site running SharePoint, it's better to place it in a dedicated web site, as described in this article:
    http://sharepointdragons.com/2011/10/07/parallel-programming-in-sharepoint-2010-the-back-to-the-future-pattern/
    It's usually too much work to get the web.config settings right because of the settings it inherits from its parents.
    Kind regards,
    Margriet Bruggeman
    Lois & Clark IT Services
    web site: http://www.loisandclark.eu
    blog: http://www.sharepointdragons.com
    I'll say that it is one solution to move the WCF Service outside of sharepoint. but my "1000 mile" requirements makes this a necessity. 
    To broaden the scope of what I am doing, I have a custom SharePoint Service Application. this custom application has a proxy that used a restful interface. Now, with all the methods i will have to write (over 100, x3 for all of the "proxy to a proxy" scenarios)
    I wanted to explore the idea of using odata. so i can use the various clients to write their own queries instead of me writing them all and exposing them. especially since its all linq queries to a database underneath. I feel that I am missing some specific
    component to make this work, and its surely due to my incomplete knowledge of WCF or EF.

  • Entity Framework -  unable to select the oracle data connection

    Entity Framework - unable to select the oracle data connection from the wizard that allows you to select the data provider. Even though we successfully added a data connection that points to an oracle database, we still can't select an existing data connection or create a new database provider that points to an oracle instance.
    we are using both vs 2008 sp1 and vs 2010. We connect to oracle 11g and we use the latest oracle odp.net driver. the Driver is installed and working in vs studio.

    I had this exact problem when I started. I think I had downloaded the wrong odbc (the 64x version). When I unloaded that version and downloaded the 32bit version it worked.
    Hope that helps. ~ Darla

  • Self Reference Model Class - How to populate using Entity Framework

    Hi,i have table in SQL Server named Employees as follows:
    EmployeeId lastName FirstName reportsTo
    1 Davolio Nancy 2
    2 Fuller Andrew NULL
    3 Leverling Janet 2
    4 Peacock Margaret 2
    5 Buchanan Steven 2
    6 Suyama Michael 5
    7 King Robert 5
    8 Callahan Laura 2
    9 Dodsworth Anne 5
    I would like to use Entity Framework to populate my Model Class .My model class looks as follows:
    public class Employees
        readonly List<Employees> _children = new List<Employees>();
        public IList<Employees> Children
            get { return _children; }
        public string FirstName { get; set; }
        public string LastName {get; set;}
    I want to use this class in ViewModel  to populate my TreeView control. Can anyone help me in order to define Linq to Entities in order to populate my model class Employees from table in SQL Server as defined. Thanks in advance.
    Almir

    Hello Fred,
    unfortunately it does not work, maybe I can be more specific about what I'm trying to get. I'm following Josh Smith's article on CodeProject related to WFP TreeView
    Josh Smith article. He has Class named Person with the following structure
    public class Person
    readonly List<Person> _children = new List<Person>();
    public List<Person> Children
    get
    return _children;
    public string Name { get; set; }
    The same is populated from Database class using method named GetFamilyTree() which look as follows:
    public static Person GetFamilyTree()
    // In a real app this method would access a database.
    return new Person
    Name = "David Weatherbeam",
    Children =
    new Person
    Name="Alberto Weatherbeam",
    Children=
    new Person
    Name="Zena Hairmonger",
    Children=
    new Person
    Name="Sarah Applifunk",
    new Person
    Name="Jenny van Machoqueen",
    Children=
    new Person
    Name="Nick van Machoqueen",
    new Person
    Name="Matilda Porcupinicus",
    new Person
    Name="Bronco van Machoqueen",
    new Person
    Name="Komrade Winkleford",
    Children=
    new Person
    Name="Maurice Winkleford",
    Children=
    new Person
    Name="Divinity W. Llamafoot",
    new Person
    Name="Komrade Winkleford, Jr.",
    Children=
    new Person
    Name="Saratoga Z. Crankentoe",
    new Person
    Name="Excaliber Winkleford",
    I'm trying to figure out how should I write
    GetFamilyTree() method using Entity Framework in order to connect to my SQL Server database and populate this Person class as it was populated manually in Joshs Example. The table I'm using in SQL Server is described in
    my first post named Employees (it's self reference table)

  • Entity Framework Query - Unable to fetch data

    I am working on a WPF application and using Entity framework 6.0
    I have written following query to fetch data from database but could not fetch any data:
    var customersList = context.Customers.Include(x => x.ReturnedCustomerItems.Select(y => y.ReturnedLotItem)).Where(x => x.IsDeleted != false).ToList();
    Notes:
    1. context: Database Context Object
    2. Customers: DbSet for Customer's table
    3. ReturnedCustomerItems: List of Customer Items to be returned.
    4. ReturnedLotItem: Lot Item corresponding to Returned Customer Item. Each Customer Item will have a corresponding lot item..
    Following is the SQL Query I have written to check whether data exits inside database:
    select * from
    transportapp.dbo.customer cust,
    transportapp.dbo.ReturnedCustomerItem ret,
    transportapp.dbo.ReturnedLotItem item
    where
    cust.CustomerId = ret.CustomerId
    and ret.BookingItemId = item.BookingItemId
    As output I got the following data records:
    Following is the Table structure generated by Entity Framework:
    CREATE TABLE [dbo].[ReturnedCustomerItem] (
    [BookingItemId] INT NOT NULL,
    [IsDeleted] BIT NOT NULL,
    [CustomerId] INT NOT NULL,
    [ReturnCharge] DECIMAL (18, 2) NOT NULL,
    [DemurrageCharge] DECIMAL (18, 2) NOT NULL,
    [Weight] DECIMAL (18, 2) NOT NULL,
    [Quantity] INT NOT NULL,
    [ReturnDate] DATETIME NOT NULL,
    [Status] NVARCHAR (100) NULL,
    CONSTRAINT [PK_dbo.ReturnedCustomerItem] PRIMARY KEY CLUSTERED ([BookingItemId] ASC),
    CONSTRAINT [FK_dbo.ReturnedCustomerItem_dbo.Customer_CustomerId] FOREIGN KEY ([CustomerId]) REFERENCES [dbo].[Customer] ([CustomerId]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.ReturnedCustomerItem_dbo.ReturnedLotItem_BookingItemId] FOREIGN KEY ([BookingItemId]) REFERENCES [dbo].[ReturnedLotItem] ([BookingItemId])
    CREATE TABLE [dbo].[ReturnedLotItem] (
    [BookingItemId] INT NOT NULL,
    [IsDeleted] BIT NOT NULL,
    [IsReturned] BIT NOT NULL,
    [ReturnCharge] DECIMAL (18, 2) NOT NULL,
    [DemurrageCharge] DECIMAL (18, 2) NOT NULL,
    [Weight] DECIMAL (18, 2) NOT NULL,
    [Quantity] INT NOT NULL,
    [LotId] INT NOT NULL,
    [LotItemId] INT NOT NULL,
    CONSTRAINT [PK_dbo.ReturnedLotItem] PRIMARY KEY CLUSTERED ([BookingItemId] ASC),
    CONSTRAINT [FK_dbo.ReturnedLotItem_dbo.BookingItem_BookingItemId] FOREIGN KEY ([BookingItemId]) REFERENCES [dbo].[BookingItem] ([BookingItemId]),
    CONSTRAINT [FK_dbo.ReturnedLotItem_dbo.ReturnedLot_LotId] FOREIGN KEY ([LotId]) REFERENCES [dbo].[ReturnedLot] ([LotId]) ON DELETE CASCADE,
    CONSTRAINT [FK_dbo.ReturnedLotItem_dbo.LotItem_LotItemId] FOREIGN KEY ([LotItemId]) REFERENCES [dbo].[LotItem] ([BookingItemId]) ON DELETE CASCADE
    I am unable to debug the LINQ expression where I am going wrong. Need help in identifying the mistake.
    Thanks!!
    NB

    The best way of debugging the SQL is to change the where portion
    1) First eliminate the 'where'
    2) Run with only one where statement  : cust.CustomerId
    = ret.CustomerId
    3) Run with the other where : ret.BookingItemId
    = item.BookingItemId
    Then compare the 3 results.  Your database may not contain any data that has both where statements true.
    jdweng

  • I can't save the record in a new/empy table of sqlserver in the entity Framework 5.0

    Hi guys ,
    I have tried to become a database expert in Entity Framework but I can't. because I am not able to save the record in a fresh/ empty table of sql server 2008 r2 database. for that I have watched the video tutorials step by steps that how to save the record.
    I followed the tutorials step by step and at the end the result is negative.
    I tried a simple way given below. please some one help me that where and what I missing the.
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using EmployeesLib;
    namespace EmpApplication
    public partial class Form1 : Form
    private EMPEntities _dbContext;
    public Form1()
    InitializeComponent();
    private void Form1_Load(object sender, EventArgs e)
    _dbContext = new EMPEntities();
    var sql = _dbContext.Employees;
    this.employeeBindingSource.DataSource = sql.ToList();
    private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    this.Validate();
    _dbContext.SaveChanges();
    I have used datagrid addid a row by Click Add button on the NavigationBindingsource entered an employee name
    and clicking the save button on the NavigationBindingSource. When I am restarting the application I nothing founding on the Datagrid I am saving before.
    below is the Connection String in the App.config file both in the project.
    APP.CONFIG connection string
        <add name="EMPEntities" connectionString="metadata=res://*/EmpModal.csdl|res://*/EmpModal.ssdl|res://*/EmpModal.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(local);initial catalog=Inventory;integrated
    security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

    humm, I falling the ball to the batsman(sqlserver) but it getting "NOBALL" in response(not saving). Ok it my be problem in visual studio I am struggling to remove my operating System, VS2013 and sql server, by reinstalling it might works.
    because i havent any other computer where these application are installed for the test.
    If you create and send me a small project that contain minimum of two columns of table( in sql server ) which can saving new data from datagrid so i will thankfull of you.
    it is just for confirmation that either the problem is in OS or VS.
    I doubt that any of it has anything to do with the issue. If you think it does, then you can post to the forums.
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vssetup
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/home?category=sqlserver
    I think you are riding a bad horse (that tutorial) you are using, and you need to change horses. I think the 'modified' state is not being rasied on the entity bound to the grid when it has changed, and EF is not going save any entity that's not in a modified
    state.

  • Entity framework code first inheritance table per type problem

    hello
    i am using ODP.NET version 11.2.0.3.20. i am trying to get entity framework code first to work. one problem i have encountered is with inheritance. i have a "table per type" inheritance scenario. i have 3 tables involved. the base table is called "S_PERIOD" which maps to the base "Period" class. i have a derived table called "S_SEASON_QUARTER" that maps to the derived "Quarter" class. And I have another derived table called "S_SEASON_PRICE_PERIOD" that maps to the derived "PriceBreak" class. for testing purposes i am trying to load all records. the problem is that every class instance ends up being of type "Quarter", which is incorrect. for whatever reason the provider thinks that every "S_PERIOD" record has a corresponding "S_SEASON_QUARTER" record. i took a look at the generated SQL and posted it down below. looking at this SQL it's clear to me why every object ends up being of type "Quarter". It looks like the provider is checking the "C2" field to determine the concrete type to instantiate. the problem however is that the "C2" field value provided by each derived table is ALWAYS equal to "1", which is a problem since this will result in the "case" statement always hitting the second "when" condition. does anyone have any idea how to fix this? thank you
    SELECT
    CASE WHEN (( NOT (("Project1"."C2" = 1) AND ("Project1"."C2" IS NOT NULL))) AND ( NOT (("Project2"."C2" = 1) AND ("Project2"."C2" IS NOT NULL)))) THEN '0X' WHEN (("Project1"."C2" = 1) AND ("Project1"."C2" IS NOT NULL)) THEN '0X0X' ELSE '0X1X' END AS "C1",
    CAST( "Extent1"."PERIOD_ID" AS number(10,0)) AS "C2",
    "Extent1"."START_DATE" AS "START_DATE",
    "Extent1"."END_DATE" AS "END_DATE",
    "Extent1"."NAME" AS "NAME",
    "Extent1"."TYPE_CODE" AS "TYPE_CODE",
    CAST( "Extent1"."CREATE_USER_ID" AS number(10,0)) AS "C3",
    "Extent1"."CREATE_DATE" AS "CREATE_DATE",
    CAST( "Extent1"."MODIFY_USER_ID" AS number(10,0)) AS "C4",
    "Extent1"."MODIFY_DATE" AS "MODIFY_DATE",
    CASE WHEN (( NOT (("Project1"."C2" = 1) AND ("Project1"."C2" IS NOT NULL))) AND ( NOT (("Project2"."C2" = 1) AND ("Project2"."C2" IS NOT NULL)))) THEN NULL WHEN (("Project1"."C2" = 1) AND ("Project1"."C2" IS NOT NULL)) THEN "Project1"."QUARTER_NAME" END AS "C5"
    FROM "DBO_SPACE_DEV"."S_PERIOD" "Extent1"
    LEFT OUTER JOIN (SELECT
         "Extent2"."QUARTER_NAME" AS "QUARTER_NAME",
         CAST( "Extent2"."QUARTER_ID" AS number(10,0)) AS "C1",
         1 AS "C2"
         FROM "DBO_SPACE_DEV"."S_SEASON_QUARTER" "Extent2" ) "Project1" ON ( CAST( "Extent1"."PERIOD_ID" AS number(10,0))) = "Project1"."C1"
    LEFT OUTER JOIN (SELECT
         CAST( "Extent3"."PRICE_PERIOD_ID" AS number(10,0)) AS "C1",
         1 AS "C2"
         FROM "DBO_SPACE_DEV"."S_SEASON_PRICE_PERIOD" "Extent3" ) "Project2" ON ( CAST( "Extent1"."PERIOD_ID" AS number(10,0))) = "Project2"."C1"
    Edited by: 997830 on Apr 3, 2013 8:40 AM

    An update:
    I tried again following this example to the letter:
    Using NuGet to Install and Configure Oracle Data Provider for .NET
    This time I used a console application as described in the example. Yes, I rebuilt the project after the NuGet install.
    I made the appropriate mods to App.config. I get the same error message as with the MVC example above.
    Does the ODP.Net driver really work with EF? If so, can anyone provide me with a working sample project?

  • Entity Framework doesn't create the database in SQL Server Management 2012, instead it just creates in (localdb)\v11.0 How to fix it?

    Hi, I'm Begginer in Entity Framework. Then I'm having some problems.
    I created my entities and I give Save Changes. (Ok)
    Then, I Tried to Connect with the database through Server Explorer, if I use the instance of the SQL Server Management Studio 2012(PC-PAULO\INSTANCIAPJ) as Server Name, the database doesn't appears but, if I use the the instance (localdb)\v11.0 the dabase
    appears.
    How to change the save to the SQL Server Management Studio 2012, I don't know where this (localDB)\v11.0 saves.
    Help-me Thank you :D

    Hello PauloJos,
    The code should be ok and it is really strange that the database is only created into the local database in your machine. I am wondering if it is related with the machine environment, could you please have a try with below demo on your machine which works
    on my side and if it is possible, please have a try to run your application on other machines to see if it works:
    class Program
    static void Main(string[] args)
    #region https://social.msdn.microsoft.com/Forums/en-US/00eff3c4-2336-4807-9212-e6f2a6c8812e/entity-framework-doesnt-create-the-database-in-sql-server-management-2012-instead-it-just-creates?forum=adodotnetentityframework
    using (CFDbContext db = new CFDbContext())
    db.Database.CreateIfNotExists();
    #endregion
    public class CFDbContext : DbContext
    public CFDbContext() : base("UltraFoda3") { }
    public DbSet<TestOne> TestOnes { get; set; }
    public class TestOne
    public int ID { get; set; }
    public string Name { get; set; }
    Config file is similar:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </configSections>
    <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
    <parameter value="v11.0" />
    </parameters>
    </defaultConnectionFactory>
    <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    </entityFramework>
    <connectionStrings>
    <add name="UltraFoda3" connectionString="Data Source=YourServer;Initial Catalog=UltraFoda3;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
    </configuration>
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Good or Bad: Repository pattern with Entity framework??

    Suggestions about not to use enttity framework because:
    1) entity framework is itself a Repository pattern
    2) So, what the use of having one more repository pattern over an exisitng repositroy pattern (i.e Entity framework)
    Please suggest.
    Thanks in advance!!

    I've used both nHibernate and the Entity Framework 6 and nHibernate wins hands down as the best orm, despite it's learning curve. ORMs can be massive timesavers as you don't end up writing boiler plate db access code.
    I used 3 different versions on nHibernate over the years. I didn't paticulalry care for any version of nHibernate. I much prefer EF over nHibernate any day of the week, month or year.
    Unlike the previous responder I disagree with testability, each repository should have it's own interface. And if implemented correctly it can save tones of time as you need only mock one or two repository methods rather than 10s or 100s of database
    gateway call using one class per table.
    What? Like a  DAO can't  have an interface, which is just as testable as any repository pattern using an interface when using a test harnerss and testproject to test the DAO? And one has to go beyond some generic repository pattern in
    unit, functional and intergation testing when it comes to data access. 
    Unlike you, I want complete control of the object all aspects of it even in its usage of other DAO(s) that could or would be used, which the  repository pattern doesn't cut it for me. 
    Like I said, I'll take EF over nHibernate, which is much like talking MS SQL Server over Oracle with Oracle being a PITA to work with it.

  • Seeding multiple databases with single Entity Framework context

    I am developing a single-instance, multi-tenant web application, with a SQL database using Entity Framework 6 Code-First. 
    I want to have a separate database for each client, generated from the same EF models, with a single DbContext. The database to connect to will be determined by the subdomain that the client is using the web app from. 
    This seems to work fine and the correct database is connected to depending on the subdomain. However my issue is seeding the databases with data. This is the code I have:
    foreach (var connString in ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>()))
    Configuration.PerformDatabaseMigration(connString.Name);
    This then calls the PerformDatabaseMigration method: 
    public class Configuration : DbMigrationsConfiguration<DataContext>
    public Configuration()
    AutomaticMigrationsEnabled = false;
    AutomaticMigrationDataLossAllowed = false;
    public static void PerformDatabaseMigration(string connStringName)
    var databaseInitialiser = new Configuration { TargetDatabase = new DbConnectionInfo(connStringName) };
    var dbMigrator = new DbMigrator(databaseInitialiser);
    dbMigrator.Update();
    protected override void Seed(DataContext context)
    base.Seed(context);
    var superAdmin = new User { Id = 1, UserName = "SuperAdmin" };
    context.Users.AddOrUpdate(superAdmin);
    The issue is that when seeding this data for the second database, the context passed into the Seed method already has the admin user added to the `DbSet<User>` property of the context, even though the context is for the second databse connection, not
    the first. It appears that the context is not being cleared from seeding the first database, and so I receive a `DbUpdateException`, as my User.Username field is a unique index.
    Cannot insert duplicate key row in object 'dbo.Users' with unique index 'IX_UserName'. The duplicate key value is (SuperAdmin).\r\nThe statement has been terminated.
    public class User : ModelBase, IUserIdentity, IPrincipal, IIdentity 
        [Index(IsUnique = true)]     
      [Required]     
      [StringLength(40)]       
    public string UserName { get; set; }

    Hello Attune,
    >>This seems to work fine and the correct database is connected to depending on the subdomain. However my issue is seeding the databases with data.
    Is that you firstly create these databases and then call the PerformDatabaseMigration method to seed these database with data? Do you have a try to seed these database data when creating the database with AutomaticMigrationsEnabled = true; with your provided
    configuration class, I tested it and it could work as seeding same data to different database:
    internal sealed class Configuration : DbMigrationsConfiguration<CFs.CFContext>
    public Configuration()
    AutomaticMigrationsEnabled = true;
    public static void PerformDatabaseMigration(string connStringName)
    var databaseInitialiser = new Configuration { TargetDatabase = new DbConnectionInfo(connStringName) };
    var dbMigrator = new DbMigrator(databaseInitialiser);
    dbMigrator.Update();
    protected override void Seed(CFs.CFContext context)
    base.Seed(context);
    var superAdmin = new ApplicationUser() { ApplicationUserID = 1, FirstName = "", LastName = "" };
    context.ApplicationUsers.AddOrUpdate(superAdmin);
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • CRVS2010 Beta - WPF / Entity Framework example?

    Has anyone been successful integrating Entity Framework objects into the CR WPF viewer?  The designer seems to work, but all we get is a blank page.  Trying to load the entities directly runs into trouble from the "not-nullable" problem and the nullable custom entities don't shoe up in the field selector (not sure why). 
    If you can share a positive experience, we'd appreciate it.

    I've been able to produce a report of our Entity Framework data by moving the data into local objects.  The WPF Report Viewer seems incapable of referring to classes in other projects of the solution.  More importantly when I try to use the Database Expert to use certain objects (tables) which link to each other through foreign keys, I am unable (because of viewer errors) to display the report.  Is anyone else working in a similar environment?

  • Declaring Navigation Property in Entity Framework

    Hi,
    I developed a sample application in EF which has 3 tables 
    PersonDetails, BankDetails and FixedDepositDetails. Please find the table structure below
    create table PersonDetails
    (PersonId int Primary Key,
    PersonName varchar(30))
    create table BankDetails
    (BankId int Primary Key,
    BankName varchar(100),
    BankBranch varchar(100),
    BankLocation varchar(100))
    create table FixedDepositDetails
    Id int Primary Key,
    FixedDepositNo varchar(30) not null,
    Bank_Id int, -- references Bank Details
    Person_Id int, -- references Person Details
    DOD datetime,
    DOM datetime,
    DepositAmount decimal(9,2),
    MaturityAmount decimal(9,2),
    ROI decimal(3,2),
    Period varchar(20),
    Parent_Id int,
    Constraint fk_BankId Foreign Key(Bank_Id) references BankDetails(BankId),
    Constraint fk_PersonId Foreign Key(Person_Id) references PersonDetails(PersonId),
    Constraint fk_ParentId Foreign Key(Parent_Id) references FixedDepositDetails(Id)
    Now in the Entity framework I have specified as given below
    [Serializable]
    public class PersonDetails
    [Key]
    public int PersonId { get; set; }
    public String PersonName { get; set; }
    [Serializable]
    public class BankDetails
    [Key]
    public int BankId { get; set; }
    public String BankName { get; set; }
    public String BankBranch { get; set; }
    public String BankLocation { get; set; }
    [Serializable]
    public class FixedDepositDetails
    [Key]
    public int Id { get; set; }
    public String FixedDepositNo { get; set; }
    [ForeignKey("Bank_Id")]
    public int? Bank_Id { get; set; }
    public BankDetails BankDetails { get; set; }
    [ForeignKey("Person_Id")]
    public int? Person_Id { get; set; }
    public PersonDetails PersonDetails { get; set; }
    public DateTime DOD { get; set; }
    public DateTime DOM { get; set; }
    public decimal DepositAmount { get; set; }
    public decimal MaturityAmount { get; set; }
    public decimal ROI { get; set; }
    public String Period { get; set; }
    [ForeignKey("Parent_Id")]
    public int? Parent_Id { get; set; }
    public FixedDepositDetails FixedDepositDetail { get; set; }
    } public class BaseDBContext : DbContext
            public BaseDBContext(string ConnectionString)
                : base(ConnectionString)
            public DbSet<PersonDetails> PersonDetails { get; set; }
            public DbSet<BankDetails> BankDetails { get; set; }
            public DbSet<FixedDepositDetails> FixedDepositDetails { get; set; }
            protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
                modelBuilder.Entity<FixedDepositDetails>()
                    .HasRequired(x => x.BankDetails)
                    .WithMany()
                    .HasForeignKey(y => y.Bank_Id);
                modelBuilder.Entity<FixedDepositDetails>()
                   .HasRequired(x => x.PersonDetails)
                   .WithMany()
                   .HasForeignKey(y => y.Person_Id);
    But when I run the application I get an error as
    The navigation property 'Bank_Id' is not a declared property on type 'FixedDepositDetails'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.
    If I am not wrong I think I have made some mistakes when creating the model. Can some some please let me know where I am doing the mistake? If some one is able to provide me with a solution Please explain me as what you are doing and why that solution needs
    to be done?
    Regards,
    Raghul

    I know this is an old thread, but when doing it either way you guys described, I get:
    "The foreign key component 'FixedDepositDetail' is not a valid navigation property on type 'PersonDetails'.
    Verify that it has not been explicitly excluded from the model and that it is a valid primitive property."
    I had my own one-to-many relationship, but for the sake of not involving new items, it mirrors this setup from above:
    public class PersonDetails
    { [Key]
    public int PersonId { get; set; }
    public String PersonName { get; set; } public virtual ICollection<FixedDepositDetails> FixedDepositDetail { get; set; }
    } public class FixedDepositDetails
    [Key]
    public int Id { get; set; } public int? Person_Id { get; set; } [ForeignKey("Person_Id")]
    public PersonDetails PersonDetails { get; set; } public FixedDepositDetails FixedDepositDetail { get; set; }
    Any ideas on how this setup should work, or is this what you guys have?

  • Using Entity Framework with Crystal Master Detail Reporting

    My project is a WPF project connected to a SQL Server Compact Edition database.  Since Crystal does not support nullable types, I have created classes specifically for the report to consume.  This is a simplified version of what I am attempting to do.
    For example...
    class Band
    public string BandName { get; set; }
    public string BandCity { get; set; }
    public List<BandRecording> RecordingsList { get; set; }
    class BandRecording
    public string Year { get; set; }
    public string Description { get; set; }
    In my code behind for this report, I am using Entity Framework to pull the data.  Just pulling information for one band...
    using (RockEntities re = new RockEntities())
    var bandinfo = (from b in re.Band
    where b.BandName == "BT"
    select new
    b.BandName,
    b.BandCity,
    Recordings = b.Recordings.OrderBy(z => z.Year)
    }).FirstOrDefault();
    OK, now I start moving to the data to class I have defined...
    Band b = new Band();
    b.RecordingsList = new List<BandRecording>();
    b.BandName = bandinfo.BandName;
    b.BandCity = bandinfo.BandCity;
    foreach(var Recording in bandinfo.Recordings)
    BandRecording br = new BandRecording();
    br.Year = Recording.Year;
    br.Description = Recording.Description;
    b.RecordingsList.Add(br);
    Since Crystal Supports IEnumerable, I create a list to hold the main record (although I am only reporting on one band)...
    List<Band> lb = new List<Band>();
    lb.Add(lb);
    ReportDocument rd = new ReportDocument();
    rd.Load("BandReport.rpt");
    rd.SetDataSource(lb);
    I have put the Band info in the Report Header section.  This is all working fine. In the details section I would like to put the Band Recording info.  I haven't figured out how to do this.  I have put the fields in the Details section, but how do I tell the details section to use the inner List<BandRecordings>?
    Any help would be greatly appreciated.

    Only way I can see of doing this would be to place emprty formulas into the section. The populate the formula(s) with the required field;
    Imports CrystalDecisions.CrystalReports.Engine
    Imports CrystalDecisions.Shared
    Public Class Form1
    Inherits System.Windows.Forms.Form
    Dim Report As New CrystalReport1()
    Dim FormulaFields As FormulaFieldDefinitions
    Dim FormulaField As FormulaFieldDefinition
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    FormulaFields = Report.DataDefinition.FormulaFields
    FormulaField = FormulaFields.Item(0)
    FormulaField.Text = "[formula text]"
    CrystalReportViewer1.ReportSource = Report
    End Sub
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Entity Framework : A short way to copy one object with it's child to a new object ?

    Hello !
    I'm using entity framework 6.
    Sometimes I need to copy an existing object with all its childs to a new object and to save to database.
    I'm using a standart way by creating a new object , copy one by one it's properties from existing object ( except the ID ) , after I create new object for every child and copy one by one each properties except the ID and Parent id......
    But of course this is a hard way to do especially when the object have a lot's of properties.
    I want to know is there any short way  ( built in) to do this ?
    Thank you !

    Actually , I'm using this extension :
    Imports System.ComponentModel
    Imports System.Collections
    Imports System.Data.Entity.Core.Objects.DataClasses
    Imports System.Runtime.Serialization
    Imports System.IO
    Imports System.Reflection
    Module Extensions
    <System.Runtime.CompilerServices.Extension> _
    Public Function Clone(Of T As EntityObject)(source As T) As T
    Dim ser = New DataContractSerializer(GetType(T))
    Using stream = New MemoryStream()
    ser.WriteObject(stream, source)
    stream.Seek(0, SeekOrigin.Begin)
    Return CType(ser.ReadObject(stream), T)
    End Using
    End Function
    <System.Runtime.CompilerServices.Extension> _
    Public Function ClearEntityReference(source As EntityObject, bCheckHierarchy As Boolean) As EntityObject
    Return source.ClearEntityObject(bCheckHierarchy)
    End Function
    <System.Runtime.CompilerServices.Extension> _
    Private Function ClearEntityObject(Of T As Class)(source As T, bCheckHierarchy As Boolean) As T
    If source Is Nothing Then
    Throw New Exception("Null Object cannot be cloned")
    End If
    Dim tObj As Type = source.[GetType]()
    If tObj.GetProperty("EntityKey") IsNot Nothing Then
    tObj.GetProperty("EntityKey").SetValue(source, Nothing, Nothing)
    End If
    If Not bCheckHierarchy Then
    Return CType(source, T)
    End If
    Dim PropertyList As List(Of PropertyInfo) = (From a In source.[GetType]().GetProperties() Where a.PropertyType.Name.Equals("ENTITYCOLLECTION`1", StringComparison.OrdinalIgnoreCase) Select a).ToList()
    For Each prop As PropertyInfo In PropertyList
    Dim keys As IEnumerable = CType(tObj.GetProperty(prop.Name).GetValue(source, Nothing), IEnumerable)
    For Each key As Object In keys
    Dim childProp = (From a In key.[GetType]().GetProperties() Where a.PropertyType.Name.Equals("EntityReference`1", StringComparison.OrdinalIgnoreCase) Select a).SingleOrDefault()
    childProp.GetValue(key, Nothing).ClearEntityObject(False)
    key.ClearEntityObject(True)
    Next
    Next
    Return CType(source, T)
    End Function
    End Module
    But the problem is that when I try to use like this :
    Dim litm, newitm as MyObject
    For Each litm In itemlist
    newitm = litm.Clone()
    newitm.ClearEntityReference(True)
    context.MyObjects.Add(newitm)
    Next
    context.SaveChanges()
    I get an error :
    Public member 'Clone' on type 'MyObject' not found.

Maybe you are looking for