开发者

Entity Framework EntityKey / Foreign Key problem

I keep getting the same error: Entities in 'VlaamseOverheidMeterEntities.ObjectMeter' participate in the 'FK_ObjectMeter_Meter' relationship. 0 related 'Meter' were found. 1 'Meter' is expected.

I have the following table structure:

Meter 1 <- * ObjectMeter * -> 1 VO_Object

It is always the same scenario: 开发者_如何学运维The first meter is added to the database, the second meter gives the error above.

I have the following code in my manager:

public List<string> addTemporary(string username, string meterNaam, string readingType, string parentID) {
        Meter meter = new Meter();
        VO_Object voObject = objectManager.getObjectByID(parentID);
        ObjectMeter objMeter = new ObjectMeter();

        meter.readingType = (int)Enum.Parse(typeof(ReadingType), readingType);
        meter.isActive = true;
        meter.name = meterNaam;
        meter.startDate = DateTime.Now;
        meter.endDate = DateTime.Now.AddYears(6000);
        meter.uniqueIdentifier = "N/A";
        meter.meterType = (int)Enum.Parse(typeof(MeterType), "NA");
        meter.meterCategory = (int)Enum.Parse(typeof(MeterCategory), "NA");
        meter.energyType = (int)Enum.Parse(typeof(EnergyType), "NA");
        meter.utilityType = (int)Enum.Parse(typeof(UtilityType), "NA");
        meter.unitOfMeasure = (int)Enum.Parse(typeof(UnitOfMeasure), "NA");

        objMeter.valid_from = meter.startDate;
        objMeter.valid_until = meter.endDate;

        objMeter.Meter = meter;
        objMeter.VO_Object = voObject;

        createMeter(meter);

        List<String> str = new List<string>();
        str.Add("" + meter.meterID);
        str.Add(meter.name);
        return str;
    }

and this in my Dao Class which links to the database:

internal void CreateMeter(Meter _meter) {
        _entities.AddToMeter(_meter);
        _entities.SaveChanges();
    }

Can someone please explain this error?

Ronald


If I understand your code: VO_Object is parent to ObjectMeter which is parent to Meter. VO_Object already exists in the database. You should create (save) ObjectMeter before creating Meter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜